码迷,mamicode.com
首页 > 其他好文 > 详细

Subtree

时间:2016-07-09 13:29:34      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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.

 Notice

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.

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

分析:
这题和考察一个字符串是否是另一个字符串的子串非常类似,需要一个一个的比。在那个题里面,用了两个for loop。这题里面我们不需要用for loop,我们只需要遍历每个node,看那个node是否和subtree的root相同,如果相同,我们就继续看左子树和右子树。
 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 }

 

Subtree

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5655637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!