Description
You have both very large binary trees: T1 , with millions of nodes, and T2 , with hundreds of nodes. Create an algorithm to decide if is T2 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 are identical to T2. That's, if you cut off the tree at node N, the both 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
解题:判断一个二叉树是不是另一个二叉树的问题。思路还是很清晰的,但是有些细节还是要注意下的。两个递归,一个用来判断两个树是否完全一样,这个只要不一样就返回false。
还有一个递归函数是用来返回最终结果的。区别在于,如果第二个函数判断不等,还有继续往T2的子树探索,知道找到一个与T1完全相等的,或者一直到最后也不存在这样的函数。
比较容易错的是,在判断结点值的时候,要先判断结点是不是null(判空)。
代码如下:
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramt1:the roots of binary tree T1. * @paramt2:the roots of binary tree T2. * @return: True If T2 is a subtree of T1, or false. */ Public Booleanequal (TreeNode T1, TreeNode T2) {if(T1 = =NULL&& T2 = =NULL){ return true; }Else if(T1 = =NULL&& T2! =NULL|| T1! =NULL&& T2 = =NULL|| T1.val! =t2.val) { return false; }Else{ returnEqual (T1.left, T2.left) &&equal (t1.right, t2.right); } } Public BooleanIssubtree (TreeNode T1, TreeNode T2) {//Write your code here if(T2 = =NULL) return true; if(T1 = =NULL) return false; if(Equal (T1, T2))return true; Else returnIssubtree (T1.left, T2) | |Issubtree (T1.right, T2); }}
245. Subtree "Lintcode Java"