Lintcode245 Subtree solution 题解

【题目描述】

You have two every 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.

Notice:A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

有两个不同大小的二叉树:T1有上百万的节点;T2有好几百的节点。请设计一种算法,判定T2是否为T1的子树。

【注】若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。

【题目链接】

www.lintcode.com/en/problem/subtree/

【题目解析】

判断 T2是否是 T1的子树,首先应该在 T1中找到 T2的根节点,找到根节点后,两棵子树必须完全相同。所以整个思路分为两步走:第一:找根节点,第二:判断两棵树是否全等。看起来很简单,但实际实现时还是细致一点,尤其要注意递归的先后顺序、条件与&条件或的处理。

【参考答案】

www.jiuzhang.com/solutions/subtree/

转载于:https://my.oschina.net/u/3776581/blog/1618917

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值