标签:
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
.
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.
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 (T2 == null) 19 return true; 20 if (T1 == null) 21 return false; 22 23 boolean[] result = new boolean[1]; 24 helper(T1, T2, result); 25 return result[0]; 26 27 } 28 29 public void helper(TreeNode T1, TreeNode T2, boolean[] result) { 30 if (T1 == null) 31 return; 32 33 if (T1.val == T2.val) { 34 if (contains(T1, T2)) { 35 result[0] = true; 36 return; 37 } 38 } 39 helper(T1.left, T2, result); 40 helper(T1.right, T2, result); 41 } 42 43 public boolean contains(TreeNode T1, TreeNode T2) { 44 if (T2 == null && T1 == null) 45 return true; 46 if (T1 == null || T2 == null) 47 return false; 48 49 if (T1.val == T2.val) { 50 return contains(T1.left, T2.left) && contains(T1.right, T2.right); 51 } 52 return false; 53 } 54 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5655637.html