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

LintCode "Subtree"

时间:2015-09-13 14:40:02      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:

A variation to Binary Tree iteration.

技术分享
class Solution {
    bool isSame(TreeNode *p1, TreeNode *p2)
    {
        if (!p1 && !p2) return true;
        if( (!p1 && p2) || (p1 && !p2) || (p1->val != p2->val))
            return false;
        return isSame(p1->left, p2->left) && 
               isSame(p1->right, p2->right);
    }
public:
    /**
     * @param T1, T2: The roots of binary tree.
     * @return: True if T2 is a subtree of T1, or false.
     */
    bool isSubtree(TreeNode *T1, TreeNode *T2) {
        if (!T2) return true;
        if (!T1 && T2) return false;
        
        queue<TreeNode *> q;
        q.push(T1);
        while(!q.empty())
        {
            auto p = q.front();
            q.pop();
            if(isSame(p, T2)) return true;
            if (p->right) q.push(p->right);
            if (p->left) q.push(p->left);
        }
        return false;
    }
};
View Code

LintCode "Subtree"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4804898.html

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