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 ofT1.

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.判断当前结点是否是子树的根节点(判断以当前节点构成的树是否与子树相同), 判断当前的左孩子是否为子树的根节点,判断当前的右孩子是否为子树的根节点。

      

 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        
19         if (T1 == null) {
20             return T1 == T2;
21         }
22         if (T2 == null) {
23             return true;
24         }
25         if (isEqual(T1, T2)){
26             return true;
27         }
28         if (isSubtree(T1.left, T2)) {
29             return true;
30         }
31         if (isSubtree(T1.right, T2)) {
32             return true;
33         }
34         return false;
35         
36     }
37 
38     private boolean isEqual(TreeNode root1, TreeNode root2) {
39         if (root1 == null && root2 == null) {
40             return true;
41         }
42         if (root1 == null || root2 == null) {
43             return root1 == root2;
44         }
45         if (root1.val != root2.val) {
46             return false;
47         }
48         return isEqual(root1.left, root2.left) && isEqual(root1.right, root2.right);
49     }
50 }

 

转载于:https://www.cnblogs.com/FLAGyuri/p/5422794.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值