算法学习之路:另一个树的子树

给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subtree-of-another-tree
 

题目不难,直接上解题过程:

package com.ucarinc.wtf.demo.Tree;

/**
 * @Package: com.ucarinc.wtf.demo.Tree
 * @ClassName: SimpleTree
 * @Author: tengfei.wu01@ucarinc.com
 * @Description:
 * @Date: 2020/5/7 14:10
 * @Version: 1.0
 */
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
package com.ucarinc.wtf.demo;

import com.ucarinc.wtf.demo.Tree.TreeNode;

/**
 * @Package: com.ucarinc.wtf.demo
 * @ClassName: IsSubtree
 * @Author: tengfei.wu01@ucarinc.com
 * @Description: 另一个树的子树
 * @Date: 2020/5/7 14:07
 * @Version: 1.0
 */
public class IsSubtree {
    public static boolean isSubtree(TreeNode s, TreeNode t) {
        //对每一个节点都进行对比
        if (isCompare(s,t)){
            return true;
        }else {
            //当s已经遍历完了,返回false
            if (s == null){
                return false;
            }else {
                //先对左节点进行遍历,再对右节点遍历
                if (isSubtree(s.left, t) || isSubtree(s.right, t)) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }
    public static boolean isCompare(TreeNode s, TreeNode t){
        //都为null说明最后一个节点已经比对过了
        if (s == null && t == null){
            return true;
        //若其中一个为null说明节点不一致
        }else if (s == null || t == null){
            return false;
        //到这步说明s和t都不为null,则对比其值,遍历左节点,遍历右节点
        }else if (s.val == t.val && isCompare(s.left,t.left) && isCompare(s.right,t.right)){
            return true;
        } else {
            return false;
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值