We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent c2a2065 commit 5f4e52aCopy full SHA for 5f4e52a
subtree-of-another-tree/TonyKim9401.java
@@ -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