另一个树的子树

标签:树 dfs

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

示例 1:
给定的树 s:

 3
/ \

4 5
/
1 2

给定的树 t:

4
/
1 2

返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。

示例 2:
给定的树 s:

 3
/ \

4 5
/
1 2
/
0

给定的树 t:

4
/
1 2

返回 false。

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

解题思路

1、暴力法

要判断一个树 t 是不是树 s 的子树,那么可以判断 t 是否和树 s 的任意子树相等。那么就转化成 100. Same Tree。
即,这个题的做法就是在 s 的每个子节点上,判断该子节点是否和 t 相等。

判断两个树是否相等的三个条件是与的关系,即:

当前两个树的根节点值相等;
并且,s 的左子树和 t 的左子树相等;
并且,s 的右子树和 t 的右子树相等。

而判断 t 是否为 s 的子树的三个条件是或的关系,即:

当前两棵树相等;
或者,t 是 s 的左子树;
或者,t 是 s 的右子树。
# 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)

2、比较 DFS 序列

class Solution:
    def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
        def dfs_sequence(root, li):
            """
            返回 DFS 序列
            """
            if root is None:
                return li
            # 必须加分隔符,要不然第 176 个用例过不了
            li.append('{' + str(root.val) + '}')
            if root.left is None:
                li.append('LeftNone')
            else:
                dfs_sequence(root.left, li)
            if root.right is None:
                li.append('RightNone')
            else:
                dfs_sequence(root.right, li)
            return li
        
        s = ','.join(dfs_sequence(s, []))
        t = ','.join(dfs_sequence(t, []))
        return t in s


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。