Leetcode 572.另一棵树的子树

572.另一棵树的子树

题目

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
示例 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。

方法

方法1:对比字符

找到tree s 和tree t 的先序遍历$s_preorder$和$t_preoder$(用字符串表示)。再检查$t_preorder$是否时$s_preorder$的字串

并且再每个可能考虑的值之前添加’#’,避免出现混淆

s:[23, 4, 5] and t:[3, 4, 5]
t(“23 4 lnull rull 5 lnull rnull”)
s(“3 4 lnull rull 5 lnull rnull”)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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
"""
return self.func(t) in self.func(s)

def func(self,node):
if not node:
return '#$'
else:
return '#'+str(node.val)+self.func(node.left)+self.func(node.right)

方法2:对比结点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 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:
return False
return self.judge(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)


def judge(self, s, t):
if s and t:
return s.val == t.val and self.judge(s.left, t.left) and self.judge(s.right, t.right)
elif not s and not t:
return True
return False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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 or not t: return not s and not t
if self.check(s, t): return True
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)

def check(self, s, t):
if not s or not t: return not s and not t
if s.val != t.val: return False
return self.check(s.left, t.left) and self.check(s.right, t.right)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 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:
return False
return self.isSame(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t)


def isSame(self,s,t):
if s and t:
return s.val==t.val and self.isSame(s.left,t.left) and self.isSame(s.right,t.right)
elif s==t:
return True
else:
return False