LintCode 245 : Subtree

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


思路:
树嘛,第一个想到用递归做。若两颗树的根结点不一样,就可以看T2是否是T1左、右子树的subtree,满足一个就可以。
若两棵树的根结点一致时,则还需要进行判断T1与T2是否是两颗相同的树。

需要注意的是,由于每个结点的数可以相同,所以即使两棵树的根结点一致并且T1和T2不相同时,还需要进行判断T2是否是T1左右子树的subTree的情况。


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


class Solution {
    bool isIdentical(TreeNode * T1, TreeNode * T2){
        if(!T1&&!T2)
            return true;
        else if(T1&&!T2 || !T1&& T2)
            return false;
        if(T1->val!=T2->val)
            return false;
        return isIdentical(T1->left,T2->left)&&isIdentical(T1->right,T2->right);
    }
public:
    /*
     * @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.
     */
    bool isSubtree(TreeNode * T1, TreeNode * T2) {
        // write your code here
        if(!T2)
            return true;
        if(!T1)
            return false;
        bool flag;
        if(T1->val==T2->val){
            flag = isIdentical(T1->left,T2->left)&&isIdentical(T1->right,T2->right);
            if(flag)
                return true;
        }
        return isSubtree(T1->left,T2)||isSubtree(T1->right,T2);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值