/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ // 解法一: funcfindTarget(root *TreeNode, k int)bool { set := map[int]struct{}{} var dfs func(*TreeNode)bool dfs = func(node *TreeNode)bool { if node == nil { returnfalse } if _, ok := set[k-node.Val]; ok { returntrue } set[node.Val] = struct{}{} return dfs(node.Left) || dfs(node.Right) } return dfs(root) } // 解法二: funcfindTarget(root *TreeNode, k int)bool { arr := []int{} var inorderTraversal func(*TreeNode) inorderTraversal = func(node *TreeNode) { if node != nil { inorderTraversal(node.Left) arr = append(arr, node.Val) inorderTraversal(node.Right) } } inorderTraversal(root)
left, right := 0, len(arr)-1 for left < right { sum := arr[left] + arr[right] if sum == k { returntrue } if sum < k { left++ } else { right-- } } returnfalse }