Subtree 解题报告

Subtree

Description

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,假设前面的节点都不满足“子树”关系,判断当前状态下,以T1为根的节点是否和T2构成子树关系,我们可以根据下面步骤判断:
1. 如果T1为空,T2还有节点,肯定不是子树关系
2. 如果T2空了,无论T1存在与否,必为子树关系
3. 如果T2往后的节点都和T1对应部分相等,则为子树关系
4. 如果前面都不满足,则找不到以T1为根的节点和T2满足子树关系。故找以T1左子树为根的节点和T1右子树为根的节点是否和T2满足字数关系

对于第3步,我们需要判断T2及其子节点是否和T1及其相应部分子节点是否全等,可以简单地做递归遍历判断,具体看以下实现:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
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) {
        // write your code here
        if(T2 != null && T1 == null){
            return false;
        }else if(T2 == null){
            return true;
        }
        if(isEqual(T1, T2)){
            return true;
        }
        return isSubtree(T1.left,T2) || isSubtree(T1.right,T2);
    }

    public boolean isEqual(TreeNode T1, TreeNode T2){
        if(T2 == null && T1 == null){
            return true;
        }else if(T2 != null && T1 != null){
            if(T1.val == T2.val && isEqual(T1.left,T2.left) && isEqual(T1.right,T2.right)){
                return true;    
            }
        }
        return false;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值