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

func equalTree(node1, node2 *TreeNode) bool {
if node1 == nil && node2 == nil {
return true
} else if node1 == nil || node2 == nil || node1.Val != node2.Val {
return false
}
return equalTree(node1.Left, node2.Left) && equalTree(node1.Right, node2.Right)
}
作者

wuhunyu

发布于

2024-08-04

更新于

2024-09-05

许可协议