Skip to content

Commit 5f4e52a

Browse files
committed
Subtree Of Another Tree
1 parent c2a2065 commit 5f4e52a

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// TC: O(n)
2+
// need to check all nodes in the worst case
3+
// SC: O(n)
4+
// recursion requires O(n) SC in the worst case
5+
class Solution {
6+
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
7+
if (root == null) return false;
8+
9+
if (sameCheck(root, subRoot)) return true;
10+
11+
return isSubtree(root.left, subRoot) ||
12+
isSubtree(root.right, subRoot);
13+
}
14+
15+
private boolean sameCheck(TreeNode root, TreeNode subRoot) {
16+
if (root == null || subRoot == null) {
17+
return root == null && subRoot == null;
18+
}
19+
20+
if (root.val != subRoot.val) return false;
21+
22+
return sameCheck(root.left, subRoot.left) &&
23+
sameCheck(root.right, subRoot.right);
24+
}
25+
}

0 commit comments

Comments
 (0)