1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
func isSubPath(head *ListNode, root *TreeNode) bool {
var dfs func(node *TreeNode, curr *ListNode) bool
dfs = func(node *TreeNode, curr *ListNode) bool {
if curr == nil {
return true // 链表遍历完,返回 true
}
if node == nil || node.Val != curr.Val {
return false // 当前节点为空或值不匹配,返回 false
}
// 继续遍历左右子树
return dfs(node.Left, curr.Next) || dfs(node.Right, curr.Next)
}
// 从根节点开始遍历
if root == nil {
return false
}
return dfs(root, head) || isSubPath(head, root.Left) || isSubPath(head, root.Right)
}
|