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 ofT1
.
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.
思路:
1.判断当前结点是否是子树的根节点(判断以当前节点构成的树是否与子树相同), 判断当前的左孩子是否为子树的根节点,判断当前的右孩子是否为子树的根节点。
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 19 if (T1 == null) { 20 return T1 == T2; 21 } 22 if (T2 == null) { 23 return true; 24 } 25 if (isEqual(T1, T2)){ 26 return true; 27 } 28 if (isSubtree(T1.left, T2)) { 29 return true; 30 } 31 if (isSubtree(T1.right, T2)) { 32 return true; 33 } 34 return false; 35 36 } 37 38 private boolean isEqual(TreeNode root1, TreeNode root2) { 39 if (root1 == null && root2 == null) { 40 return true; 41 } 42 if (root1 == null || root2 == null) { 43 return root1 == root2; 44 } 45 if (root1.val != root2.val) { 46 return false; 47 } 48 return isEqual(root1.left, root2.left) && isEqual(root1.right, root2.right); 49 } 50 }