天天看点

LintCode Subtree

原题链接在这里:http://www.lintcode.com/en/problem/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

.

Have you met this question in a real interview? 

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
           

Note

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 /**
 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         // write your code here
19         if(T2 == null){
20             return true;
21         }
22         if(T1 == null){
23             return false;
24         }
25         return isSame(T1,T2) || isSubtree(T1.left, T2) || isSubtree(T1.right, T2);
26     }
27     
28     private boolean isSame(TreeNode T1, TreeNode T2){
29         if(T1 == null && T2 == null){
30             return true;
31         }
32         if(T1 == null || T2 == null){
33             return false;
34         }
35         if(T1.val != T2.val){
36             return false;
37         }
38         return isSame(T1.left, T2.left) && isSame(T1.right, T2.right);
39     }
40 }