Skip to content

Commit b69aa8a

Browse files
committed
feat: subtree-of-another-tree
1 parent 6679bf9 commit b69aa8a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* <a href="https://leetcode.com/problems/subtree-of-another-tree/">week15-1. subtree-of-another-tree</a>
3+
* <li>Description: Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot </li>
4+
* <li>Topics: Tree, Depth-First Search, String Matching, Binary Tree, Hash Function</li>
5+
* <li>Time Complexity: O(N*M), Runtime 2ms </li>
6+
* <li>Space Complexity: O(H), Memory 43.98MB </li>
7+
*/
8+
class Solution {
9+
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
10+
if (root == null) return false;
11+
if (isSameTree(root, subRoot)) return true;
12+
return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
13+
}
14+
15+
public boolean isSameTree(TreeNode root, TreeNode subRoot) {
16+
if (root == null && subRoot == null) return true;
17+
if (root == null || subRoot == null) return false;
18+
if (root.val != subRoot.val) return false;
19+
return isSameTree(root.left, subRoot.left) && isSameTree(root.right, subRoot.right);
20+
}
21+
}

0 commit comments

Comments
 (0)