public class Solution {
    /**
     * @param T1, T2: The roots of binary tree.
     * @return: True if T2 is a subtree of T1, or false.
     */
    public boolean isSubtree(TreeNode T1, TreeNode T2) {
        
        if (T1 == null && T2 == null){
            return true;
        }else if (T1 == null){
            return false;
        }else if (T2 == null){
            return true;
        }
        //actually here it still looks like divide & conquer in that there are three possibilities that is subtree: the root itself, the left child and right child
        //and if the root itself is a subtree, then it must be the same tree
        return isSameTree(T1, T2) || isSubtree(T1.left, T2) || isSubtree(T1.right, T2);
    }
    public boolean isSameTree(TreeNode p, TreeNode q){
        if (p == null && q == null){
            return true;
        }else if (p == null || q == null){
            return false;
        }else if (p.val != q.val){
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

liut2的算法笔记
0 声望1 粉丝

« 上一篇
一点recursion
下一篇 »
Two Sum问题

引用和评论

0 条评论