子树(LintCode) .

子树

有两个不同大小的二进制树: T1 有上百万的节点;T2 有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。

样例

下面的例子中 T2 是 T1 的子树:

       1                3
      / \              / 
T1 = 2   3      T2 =  4
        /
       4

下面的例子中 T2 不是 T1 的子树:

       1               3
      / \               \
T1 = 2   3       T2 =    4
        /
       4
注意

若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。

先用递归在T1中找出可能的子树的根节点,然后检验以这个节点为根的子树与T2是否完全相同。

这里我偷懒就直接用了同一个方法,用一个参数i标记是要验证完全相同还是要找可能的根节点。

 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 && T2 == null) return true;
19         if(T1 == null && T2 != null) return false;
20         if(T1 != null && T2 == null) return true;
21         return solve(T1,T2, 0);
22         
23     }
24     
25     public boolean solve(TreeNode T1, TreeNode T2, int i) {
26         if(T1 == null && T2 == null) return true;
27         if(T1 == null && T2 != null) return false;
28         if(T1 != null && T2 == null) return false;
29         if(T1.val == T2.val) {
30             if(solve(T1.left,T2.left,1) && (solve(T1.right,T2.right,1)))
31                 return true;
32         }
33         if(i == 0) {
34             boolean f = false;
35             if(T1.left != null) f = solve(T1.left, T2,0);
36             else f = false;
37             if(T1.right != null) f = f || solve(T1.right, T2,0);
38             else f = f || false;
39             return f;
40         }
41         return false;
42     }
43 }
View Code
原文地址:https://www.cnblogs.com/FJH1994/p/5022665.html