<剑指offer> 第15题
发布日期:2021-08-15 09:34:12 浏览次数:6 分类:技术文章

本文共 1308 字,大约阅读时间需要 4 分钟。

题目:

输入两棵二叉树A和B,判断B是不是A的子结构

思路:

分为两步:

(1)在树A中找到和B的根节点的值一样的节点R

(2)判断树A中以R为根节点的子树是不是包含和树B一样的结构

public class Fifteenth {    public static class BinaryTreeNode{        int value;        BinaryTreeNode left;        BinaryTreeNode right;    }    public static boolean hasSubtree(BinaryTreeNode root1, BinaryTreeNode root2){        if(root1 == root2){            return true;        }        if(root2 == null){            return true;        }        if(root1 == null){            return false;        }        //记录匹配结果        boolean result = false;        //如果节点的值相等就调用匹配方法        if(root1.value == root2.value){            result = match(root1, root2);        }        //如果匹配就直接返回结果        if(result){            return true;        }        return hasSubtree(root1.left, root2) || hasSubtree(root1.right, root2);    }    public static boolean match(BinaryTreeNode root1, BinaryTreeNode root2){        //只要两个对象是同一个就返回true        if(root1 == root2){            return true;        }        if(root2 == null){            return true;        }        if(root1 == null){            return false;        }        if(root1.value == root2.value){            return match(root1.left, root1.left) && match(root1.right, root2.right);        }        return false;    }}

 

转载于:https://www.cnblogs.com/HarSong13/p/11329758.html

转载地址:https://blog.csdn.net/weixin_30757793/article/details/99660579 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:tensorflow下载和安装
下一篇:反射总结

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2024年03月30日 06时53分42秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

spring boot 与 Ant Design of Vue 实现新增组织(二十四) 2019-04-27
spring boot 与 Ant Design of Vue 实现修改组织(二十五) 2019-04-27
spring boot 与 Ant Design of Vue 实现删除组织(二十六) 2019-04-27
spring boot 与 Ant Design of Vue 实现获取用户列表(二十七) 2019-04-27
spring boot 与 Ant Design of Vue 实现新增用户(二十八) 2019-04-27
spring boot 与 Ant Design of Vue 实现修改用户(二十九) 2019-04-27
spring boot 与 Ant Design of Vue 实现删除用户(三十) 2019-04-27
spring boot 与 Ant Design of Vue 鉴权体系登录的实现(三十一) 2019-04-27
spring boot 与 Ant Design of Vue 鉴权体系获取用户信息的实现(三十二) 2019-04-27
Druid连接池实现自定义场景的多数据库的连接 2019-04-27
CentOs7命令行(静默)的方式安装oracle数据库 2019-04-27
基于VMware安装CentOs7的镜像 2019-04-27
PL/SQL数据库管理工具的使用 2019-04-27
带你玩转属于自己的spring-boot-starter系列(一) 2019-04-27
带你玩转属于自己自己的spring-boot-starter系列(二) 2019-04-27
带你玩转属于自己的spring-boot-starter系列(三) 2019-04-27
基于SnowFlake算法如何让分库分表中不同的ID落在同一个库的算法的实现 2019-04-27
基于springboot的ShardingSphere5.X的分库分表的解决方案之分库解决方案(二) 2019-04-27
基于springboot的ShardingSphere5.X的分库分表的解决方案之分表解决方案(一) 2019-04-27
基于springboot的ShardingSphere5.X的分库分表的解决方案之关联查询解决方案(三) 2019-04-27