653. 两数之和 IV - 输入二叉搜索树 - 力扣(Leetcode)
用了迭代进行遍历二叉树,因为二叉搜索树的中序遍历是有序的,所以肯定左边大于右边,然后就可以用一个map
来存放之前的数值,
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findTarget(root *TreeNode, k int) bool {
if root == nil {
return false
}
m := make(map[int]struct{})
stack := []*TreeNode{}
cur := root
for cur != nil || len(stack) > 0 {
for cur != nil {
stack = append(stack, cur)
cur = cur.Left
}
cur = stack[len(stack) - 1]
stack = stack[:len(stack)-1]
if _, ok := m[k-cur.Val]; ok {
return true
}
m[cur.Val] = struct{}{}
cur = cur.Right
}
return false
}
标签:二叉,TreeNode,cur,Val,leetcode,IV,stack,两数
From: https://www.cnblogs.com/wudanyang/p/17026395.html