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

Subtree(子树)_第1张图片

T2 isn't a subtree of T1 in the following case:

Subtree(子树)_第2张图片

分析

三点需要注意的:
1,当T1的节点跟T2的节点不相同时,T1的左子树和右子树只要有一个符合就是正确的。
2,当T1的节点跟T2相同时,因为T1中的节点可能值会有重复,所以这个不符合不能保证所有的不符合。
3,当T1的节点跟T2相同时,完全符合的条件是T1的左右子节点跟T2的左右子节点完全相同。

代码

 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param T1: The roots of binary tree T1.
     * @param T2: The roots of binary tree T2.
     * @return: True if T2 is a subtree of T1, or false.
     */
    
    public boolean isSubtree(TreeNode T1, TreeNode T2) {
        // write your code here
        if(T2==null){
            return true;
        }
        if(T1==null){
            return false;
        }
        if(isSame(T1,T2)){
            return true;
        }
        return isSubtree(T1.left,T2)||isSubtree(T1.right,T2);
    }
    private boolean isSame(TreeNode t1,TreeNode t2){
        if(t1==null||t2==null){
            return t1==t2;
        }
        if(t1.val==t2.val){
            return isSame(t1.left,t2.left)&&isSame(t1.right,t2.right);
        }
        return false;
    }
    
};

你可能感兴趣的:(Subtree(子树))