Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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
posted on 2015-09-13 14:07  Tonix  阅读(193)  评论(0编辑  收藏  举报