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

CTCI 4.8

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

标签:des   style   blog   http   color   for   

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

标签:des   style   blog   http   color   for   

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

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