leetcode-653. 两数之和 IV - 输入二叉搜索树

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
}
posted @ 2023-01-05 00:12  吴丹阳-V  阅读(26)  评论(0编辑  收藏  举报