24、树的子结构——剑指offer

树的子结构

问题描述:判断二叉树B是不是二叉树A的子结构


    首先考察基本功,先找到根节点一样的节点,然后递归的判断左子树和右子树,类似于前序遍历

    本方法思想:先找到根节点一样的节点,然后递归的判断左子树和右子树,类似于前序遍历


持续更新...

代码附下

Java实现:

package 树的子结构;
//二叉树的数据结构
public class BinaryTree {
    int val;
    BinaryTree left = null;
    BinaryTree right = null;
    public BinaryTree(int val) {
        this.val = val;
    }
}

public class hasSubTree {
    public static int count = 1;//计数用,记录遍历第几次找到子树结构
    public static void main(String[] args) {//main方法构建一棵二叉树
        /**
         * A B 树 8 8 8 7 9 2 9 2 4 7
         */
        BinaryTree rootA = new BinaryTree(8);
        rootA.left = new BinaryTree(8);
        rootA.right = new BinaryTree(7);
        rootA.left.left = new BinaryTree(9);
        rootA.left.right = new BinaryTree(2);
        rootA.left.right.left = new BinaryTree(4);
        rootA.left.right.right = new BinaryTree(7);
        BinaryTree rootB = new BinaryTree(2);
        rootB.left = new BinaryTree(4);
        rootB.right = new BinaryTree(7);
        System.out.println(hasSubTree(rootA, rootB));//测试用例
    }

    //B是否为A的子树
    public static boolean hasSubTree(BinaryTree rootA, BinaryTree rootB) {
        boolean result = false;
        if (rootA != null && rootB != null) {
            if (rootA.val == rootB.val) {//根相同时才有可能是子树
                result = DoesTreeAHasTreeB(rootA, rootB);
                if (result) {
                    System.out.println("这是第" + count + "次遍历,其中包括遍历了空节点");
                }
            }
            if (!result) {//根不同,找左子树
                count++;
                result = hasSubTree(rootA.left, rootB);
            }
            if (!result) {//左子树不相同找右子树
                count++;
                result = hasSubTree(rootA.right, rootB);
            }
        }
        return result;
    }

    //如果根相同,判断B是否为A的子树
    private static boolean DoesTreeAHasTreeB(BinaryTree rootA, BinaryTree rootB) {
        if (rootB == null) {//B没有时就是相同了
            return true;
        }
        if (rootA == null) {
            return false;
        }
        if (rootA.val != rootB.val) {//值不相等肯定不是子树
            return false;
        }
        return DoesTreeAHasTreeB(rootA.left, rootB.left) && DoesTreeAHasTreeB(rootA.right, rootB.right);//递归判断左右子树
    }
}

持续更新...欢迎赞赏!

主页:https://blog.csdn.net/ustcer_93lk/article/details/80374008

如果有问题,欢迎大家留言,有更好的方法也期待大家告知。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值