T1
, with millions of nodes, and T2
, with hundreds of nodes. Create an algorithm to decide if T2
is a subtree of T1
.Example
T2 is a subtree of T1 in the following case:
1 3
/ \ /
T1 = 2 3 T2 = 4
/
4
T2 isn't a subtree of T1 in the following case:
1 3
/ \ \
T1 = 2 3 T2 = 4
/
4
/**
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
//time:O(mn), space:O(1)
public class Solution {
public boolean isSubtree(TreeNode T1, TreeNode T2) {
if (T2 == null) {
return true;
}
if (T1 == null) {
return false;
}
if (identical(T1, T2)) {
return true;
}
if (isSubtree(T1.left, T2) || isSubtree(T1.right, T2)) {
return true;
}
return false;
}
public boolean identical(TreeNode root1, TreeNode root2) {
if (root1 == null || root2 == null) {
return root1 == root2;
}
if (root1.val != root2.val) {
return false;
}
return identical(root1.left, root2.left) &&
identical(root1.right, root2.right);
}
}
No comments:
Post a Comment