leetcode 572. 另一个树的子树

题解

递归判断两个二叉树是否相同

示例代码(go)

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
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSubtree(s *TreeNode, t *TreeNode) bool {
if s == nil && t != nil {
return false
}
return isSame(s, t) || isSubtree(s.Left, t) || isSubtree(s.Right, t)
}

func isSame(s *TreeNode, t *TreeNode) bool {
if s != nil && t == nil {
return false
}
if s == nil && t != nil {
return false
}
if s == nil && t == nil {
return true
}
if s.Val != t.Val {
return false
}
return isSame(s.Left, t.Left) && isSame(s.Right, t.Right)
}