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
.
Yes
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
package campus.lintCode; public class SubTree { public static void main(String[] args) { TreeNode treeNode1 = new TreeNode(1); TreeNode treeNode21 = new TreeNode(1); TreeNode treeNode22 = new TreeNode(1); TreeNode treeNode31 = new TreeNode(2); TreeNode treeNode32 = new TreeNode(3); TreeNode treeNode34 = new TreeNode(2); TreeNode treeNode43 = new TreeNode(4); TreeNode treeNode44 = new TreeNode(5); TreeNode treeNode45 = new TreeNode(3); treeNode1.left = treeNode21; treeNode1.right = treeNode22; treeNode21.left = treeNode31; treeNode21.right = treeNode32; treeNode22.right = treeNode34; treeNode32.left = treeNode43; treeNode32.right = treeNode44; treeNode34.left = treeNode45; TreeNode treeNode212 = new TreeNode(1); TreeNode treeNode312 = new TreeNode(2); TreeNode treeNode322 = new TreeNode(3); TreeNode treeNode432 = new TreeNode(4); TreeNode treeNode442 = new TreeNode(5); treeNode212.left = treeNode312; treeNode212.right = treeNode322; treeNode322.left = treeNode432; treeNode322.right = treeNode442; SubTree subTree = new SubTree(); System.out.println(subTree.isSubtree(treeNode1, treeNode212)); //System.out.println(subTree.priorSubtree(treeNode1,treeNode212)); } /** * @param T1, T2: The roots of binary tree. * @return: True if T2 is a subtree of T1, or false. */ public boolean isSubtree(TreeNode T1, TreeNode T2) { // write your code here boolean result = false; // 如何child=NULL,则说明child已经到达叶子了,无论parent是否到达一个叶子节点,都应该返回真 if (T2 == null) { return true; } // 首先,如果程序执行到这里,则child一定不是NULL,如果parent=NULL,则说明parent不包含child if (T1 == null) { return false; } if (T1.val == T2.val) {// 当if条件满足的时候,则继续递归判断它们的左子树和右子树是否相等,只有两者相等才返回真 result = isSubtreeDef(T1,T2); } if(!result) { result= (isSubtree(T1.left, T2) || isSubtree(T1.right, T2)); } return result; } public boolean isSubtreeDef(TreeNode T1, TreeNode T2) { // write your code here // 如何child=NULL,则说明child已经到达叶子了,无论parent是否到达一个叶子节点,都应该返回真 if (T2 == null&&T1 == null) { return true; } if (T1!=null&&T2!=null&&T1.val == T2.val) {// 当if条件满足的时候,则继续递归判断它们的左子树和右子树是否相等,只有两者相等才返回真 return (isSubtreeDef(T1.left, T2.left) && isSubtreeDef(T1.right, T2.right)); } return false; } } class TreeNode { public int val; public TreeNode left, right; public TreeNode(int val) { this.val = val; this.left = this.right = null; } }