博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
572. Subtree of Another Tree
阅读量:2352 次
发布时间:2019-05-10

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

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.

我的想法

用递归来写。但这样写对于[1,1] [1]这样的corner case会错判为false,因为在根结点发现相等后就已经往下判断结构了。

class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s == null || t == null) {
return s == t ? true : false; } if(s.val == t.val) {
//注意这里是&&保证结构相同 return isSubtree(s.left, t.left) && isSubtree(s.right, t.right); } //这里是||只要左右子树有一个满足就为真 return isSubtree(s.left, t) || isSubtree(s.right, t); }}

解答

看了下答案之后发现,只要把整个函数拆成两个步骤递归即可。第一个递归比较的根结点,第二个递归比较结构是否相同

class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s == null || t == null) {
return s == t ? true : false; } if(s.val == t.val && compare(s, t)) {
return true; } return isSubtree(s.left, t) || isSubtree(s.right, t); } private boolean compare(TreeNode s, TreeNode t) {
if(s == null || t == null) {
return s == t ? true : false; } if(s.val != t.val) {
return false; } return compare(s.left, t.left) && compare(s.right, t.right); }}

转载地址:http://xyqvb.baihongyu.com/

你可能感兴趣的文章
Axis,axis2,Xfire以及cxf对比
查看>>
【工具】人脸识别比对开放平台汇总
查看>>
基于DirectUI技术开发的发卡系统
查看>>
STM32 HAL库、标准外设库、LL库(STM32 Embedded Software)
查看>>
51和AVR单片机
查看>>
DSP开发板
查看>>
stm32标准外设库和芯片资料下载地址
查看>>
ARM Keil MDK开发STM32工程模板
查看>>
NoSQL分类及常用软件
查看>>
ubuntu 16.04安装nVidia显卡驱动和cuda/cudnn踩坑过程
查看>>
基于STM32CubeMX创建STM32L496ZGTx的工程
查看>>
如何通过OpenFace实现人脸识别框架
查看>>
Angle和XBGoost以及Spark的性能对比
查看>>
IOS CoreImage实现人脸识别
查看>>
Tensorflow的高级封装
查看>>
Storm 1.1.0 集群安装
查看>>
图像压缩算法
查看>>
一张图看懂小程序全生态
查看>>
electron开发
查看>>
NodeJS开发c++扩展模块
查看>>