首页 > 其他 > 详细

CTCI 4.8

时间:2014-07-13 13:04:20      阅读:262      评论:0      收藏:0      [点我收藏+]

You have two very 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. A tree T2 is a subtree of T1 if there exist a node in T1 such that the subtree of nis identical to T2. That is, if you cut off the tree at node n, the two trees would be indentical.

You could test the function to determine whether the two tree is the same here, https://oj.leetcode.com/problems/same-tree/

/* For each node in T1, we determin if T2 is a subtree of T1, if not, we recursively find the T1‘s left 
subtree and T1‘s right subtree.*/

public class IsSubTree {
    public boolean issubtree(TreeNode root, TreeNode t) {
        // Empty tree is subtree of any tree
        if(t == null) return true;
        if(root == null) {
            // Empty tree could have no subtrees except for empty tree
            return false;
        }
        else {
            if(issame(root, t) == true) return true;
            return issubtree(root.left, t) | issubtree(root.right, t);
        }
    }

    public boolean issame(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 issame(p.left, q.left) & issame(p.right, q.right);
        }
    }
}

 

CTCI 4.8,布布扣,bubuko.com

CTCI 4.8

原文:http://www.cnblogs.com/pyemma/p/3840794.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!