作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/subtree-of-another-tree/#/description

题目描述

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.

Example 1:

Given tree s:

     3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.

Example 2:

Given tree s:

     3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.

题目大意

判断 t 是不是 s 的一个子树。

解题方法

方法一:先序遍历

先序遍历把树转成字符串,判断是否为子串。

在当节点为空的时候给一个“#”表示,这样就能表示出不同的子树,因此只需要遍历一次就能得到结果。每次遍历到树的结尾的时候能够按照#区分,另外每个树的节点值之间用","分割。
在提交的时候又遇到一个问题,就是12和2的结果是一样的,那么我在每个遍历结果的开头位置再加上一个逗号就完美解决了。
另外注意,不要判断左右子树不为空再去遍历树,这样就不能添加上“#”了。

Java 代码如下:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
StringBuilder spre = new StringBuilder();
StringBuilder tpre = new StringBuilder();
public boolean isSubtree(TreeNode s, TreeNode t) {
preOrder(s, spre.append(","));
preOrder(t, tpre.append(","));
System.out.println(spre.toString());
System.out.println(tpre.toString());
return spre.toString().contains(tpre.toString());
}
public void preOrder(TreeNode root, StringBuilder str){
if(root == null){
str.append("#,");
return;
}
str.append(root.val).append(",");
preOrder(root.left, str);
preOrder(root.right, str);
}
}

方法二:DFS + DFS

要判断一个树 t 是不是另外一个树 s 的子树,那么可以判断 t 是否和树 s 的任意子树是否相等。那么就和100. Same Tree挺像了。所以这个题的做法就是在判断两棵树是否相等的基础上,添加上任意子树是否相等的判断。

判断 t 是否为 s 的子树的方式是:

  1. 当前两棵树相等;
  2. 或者,s 的左子树和 t 相等
  3. 或者,s 的左子树和 t 相等

这三个条件是的关系。

注意,判断两个树是否相等是的关系,即:

  1. 当前两个树的根节点值相等
  2. 并且,s 的左子树和 t 的左子树相等
  3. 并且,s 的左子树和 t 的右子树相等

判断是否是子树与是否是相同的树的代码简直是对称美啊~

Python代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if not s and not t:
return True
if not s or not t:
return False
return self.isSameTree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t) def isSameTree(self, s, t):
if not s and not t:
return True
if not s or not t:
return False
return s.val == t.val and self.isSameTree(s.left, t.left) and self.isSameTree(s.right, t.right)

方法三:BFS + DFS

因为 t 的根节点可能对应着 s 中的任意一个节点,那么我们使用 BFS 来遍历 s 的每个节点,然后对每个节点进行判断是否与 t 相等。

Python代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if not s and not t:
return True
if not s or not t:
return False
que = collections.deque()
que.append(s)
while que:
node = que.popleft()
if not node:
continue
if self.isSameTree(node, t):
return True
que.append(node.left)
que.append(node.right)
return False def isSameTree(self, s, t):
if not s and not t:
return True
if not s or not t:
return False
return s.val == t.val and self.isSameTree(s.left, t.left) and self.isSameTree(s.right, t.right)

日期

2017 年 5 月 9 日
2018 年 10 月 19 日 —— 自古逢秋悲寂寥,我言秋日胜春朝
2018 年 11 月 21 日 —— 又是一个美好的开始
2020年 5 月 7 日 —— 先把工作忙完,再搞其他的

【LeetCode】572. 另一个树的子树 Subtree of Another Tree(Python & Java)的更多相关文章

  1. LeetCode 572. 另一个树的子树(Subtree of Another Tree) 40

    572. 另一个树的子树 572. Subtree of Another Tree 题目描述 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树.s 的一个子树包括 ...

  2. [程序员代码面试指南]二叉树问题-判断t1树是否包含t2树的全部拓扑结构、[LeetCode]572. 另一个树的子树

    题目1 解 先序遍历树1,判断树1以每个节点为根的子树是否包含树2的拓扑结构. 时间复杂度:O(M*N) 注意区分判断总体包含关系.和判断子树是否包含树2的函数. 代码 public class Ma ...

  3. LeetCode 572. 另一个树的子树 | Python

    572. 另一个树的子树 题目来源:https://leetcode-cn.com/problems/subtree-of-another-tree 题目 给定两个非空二叉树 s 和 t,检验 s 中 ...

  4. Java实现 LeetCode 572 另一个树的子树(遍历树)

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

  5. LeetCode 572. 另一个树的子树

    题目链接:https://leetcode-cn.com/problems/subtree-of-another-tree/ 给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和 ...

  6. 力扣Leetcode 572. 另一个树的子树

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

  7. [Swift]LeetCode572. 另一个树的子树 | Subtree of Another Tree

    Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and no ...

  8. [LeetCode] Subtree of Another Tree 另一个树的子树

    Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and no ...

  9. LeetCode算法题-Subtree of Another Tree(Java实现)

    这是悦乐书的第265次更新,第278篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第132题(顺位题号是572).给定两个非空的二进制树s和t,检查树t是否具有完全相同的 ...

随机推荐

  1. R语言与医学统计图形-【23】ggplot2坐标系转换函数

    ggplot2绘图系统--坐标系转换函数 包括饼图.环状条图.玫瑰图.戒指图.坐标翻转. 笛卡尔坐标系(最常见). ArcGIS地理坐标系(地图). Cartesian坐标系. polar极坐标系. ...

  2. 多组学分析及可视化R包

    最近打算开始写一个多组学(包括宏基因组/16S/转录组/蛋白组/代谢组)关联分析的R包,避免重复造轮子,在开始之前随便在网上调研了下目前已有的R包工具,部分罗列如下: 1. mixOmics 应该是在 ...

  3. CentOS安装配置Hadoop 1.2.1(伪分布模式)

    CentOS安装配置Hadoop1.2.1 1.下载安装文件 下载2个安装文件 JAVA环境:jdk-6u21-linux-i586.bin Hadoop环境:hadoop-1.2.1.tar.gz ...

  4. Excel-返回列表或数据库中的分类汇总(汇总可以实现要还是不要统计隐藏行功能) subtotal()

    SUBTOTAL函数 函数名称:SUBTOTAL 主要功能:返回列表或数据库中的分类汇总. 使用格式:SUBTOTAL(function_num, ref1, ref2, ...) 参数说明:Func ...

  5. 23-Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. Examples: Giv ...

  6. 学习java 6.29

    今天是学习Java的第一天. 学习内容:了解了JDK的下载和安装: 学会了如何配置Path环境变量及安装eclipse: 执行了HelloWorld案例: 在Java中关键字需要小写,Java中最基本 ...

  7. C/C++ Qt 数据库与ComBox多级联动

    Qt中的SQL数据库组件可以与ComBox组件形成多级联动效果,在日常开发中多级联动效果应用非常广泛,例如当我们选择指定用户时,我们让其在另一个ComBox组件中列举出该用户所维护的主机列表,又或者当 ...

  8. STM32一些特殊引脚做IO使用的注意事项

    1 PC13.PC14.PC15的使用 这三个引脚与RTC复用,<STM32参考手册>中这样描述: PC13 PC14 PC15需要将VBAT与VDD连接,实测采用以下程序驱动4个74HC ...

  9. android转换透明度

    比方说 70% 白色透明度. 就用255*0.7=185.5  在把185.5转换成16进制就是B2 你只需要写#B2FFFFFF 如果是黑色就换成6个0就可以了.前2位是控制透明度的.

  10. 设置linux下oracle开机自启动

    1.修改配置文件,vi /etc/oratab orcl:/u01/app/oracle/product/11.2.0/db_1:Y 2.创建启动文件,/etc/init.d/ #!/bin/sh # ...