File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ # Time Complexity: O(n)
3+ # Space Complexity: O(n)
4+ - 재귀 호출 파라미터 O(n) 사이즈 공간 필요
5+ */
6+
7+ /**
8+ * Definition for a binary tree node.
9+ * public class TreeNode {
10+ * int val;
11+ * TreeNode left;
12+ * TreeNode right;
13+ * TreeNode() {}
14+ * TreeNode(int val) { this.val = val; }
15+ * TreeNode(int val, TreeNode left, TreeNode right) {
16+ * this.val = val;
17+ * this.left = left;
18+ * this.right = right;
19+ * }
20+ * }
21+ */
22+ class Solution {
23+ public boolean isSubtree (TreeNode root , TreeNode subRoot ) {
24+ return dfs (root , subRoot );
25+ }
26+
27+ private boolean dfs (TreeNode root , TreeNode subRoot ) {
28+ if (root == null && subRoot == null ) return true ;
29+ if (root == null || subRoot == null ) return false ;
30+
31+ if (root .val == subRoot .val ) {
32+ if (compareTrees (root , subRoot )) return true ;
33+ }
34+
35+ if (dfs (root .left , subRoot )) return true ;
36+ if (dfs (root .right , subRoot )) return true ;
37+
38+ return false ;
39+ }
40+
41+ private boolean compareTrees (TreeNode root1 , TreeNode root2 ) {
42+ if (root1 == null && root2 == null ) return true ;
43+ if (root1 == null || root2 == null ) return false ;
44+ if (root1 .val != root2 .val ) return false ;
45+
46+ return compareTrees (root1 .left , root2 .left ) && compareTrees (root1 .right , root2 .right );
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments