九章算法 | ebay面试题:另一个树的子树

描述

给定两个非空二叉树st,检查树t是否和树s的一个子树具有完全相同的结构和节点值。 s的子树是一个由s中的一个节点和该节点的后续组成的树。 树s本身也可以被视为自己的一个子树。

在线评测地址

样例1

给出树s:

     3
    / \
   4   5
  / \
 1   2
给出树t:
   4 
  / \
 1   2
返回true,因为t和s的子树具有完全相同的结构和节点值。

样例2

给出树s:

     3
    / \
   4   5
  / \
 1   2
    /
   0
给出树t:
   4
  / \
 1   2
返回false.

解题思路

在遍历树的同时,当树t的根节点值与树s的某个节点值相等时,比较树t与树s的这个子树,相同则返回true.

源代码

/**
 * 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 s: the s' root
     * @param t: the t' root
     * @return: whether tree t has exactly the same structure and node values with a subtree of s
     */
    public boolean isSubtree(TreeNode s, TreeNode t) {
        // Write your code here
        if(s == null) return t == null;
        if(s.val == t.val && compare(s,t) ) return true;
        return isSubtree(s.left, t) || isSubtree(s.right, t);
    }

    boolean compare(TreeNode s, TreeNode t) {
        if(s == null) return t == null;
        if(t == null || s.val != t.val) return false;
        return compare(s.left, t.left) && compare(s.right, t.right);
    }
}

更多题解参考

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值