CTCI 4.8

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);
        }
    }
}

 

转载于:https://www.cnblogs.com/pyemma/p/3840794.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值