Subtree
You have two every large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
Notice
A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.
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
1 /** 2 * Definition of TreeNode: 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param T1, T2: The roots of binary tree. 15 * @return: True if T2 is a subtree of T1, or false. 16 */ 17 public boolean isSubtree(TreeNode T1, TreeNode T2) { 18 if (T1 == null) { 19 return T2 == T1; 20 } 21 if (T2 == null) { 22 return true; 23 } 24 if (isEqual(T1, T2)) { 25 return true; 26 } 27 if (isSubtree(T1.left, T2)) { 28 return true; 29 } 30 if (isSubtree(T1.right, T2)) { 31 return true; 32 } 33 return false; 34 } 35 36 private boolean isEqual(TreeNode T1, TreeNode T2) { 37 if (T1 == null) { 38 return T2 == T1; 39 } 40 if (T2 == null) { 41 return false; 42 } 43 if (T1.val != T2.val) { 44 return false; 45 } 46 return isEqual(T1.left, T2.left) && isEqual(T1.right, T2.right); 47 } 48 }

浙公网安备 33010602011771号