Back to Leetcode Go

653. Two Sum IV - Input is a BST

website/content.en/ChapterFour/0600~0699/0653.Two-Sum-IV-Input-is-a-BST.md

1.7.971.6 KB
Original Source

653. Two Sum IV - Input is a BST

Problem

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 9

Output: True

Example 2:

Input: 
    5
   / \
  3   6
 / \   \
2   4   7

Target = 28

Output: False

Problem Summary

Given a binary search tree and a target result, if there exist two elements in the BST and their sum is equal to the given target result, return true.

Solution Ideas

  • Determine whether there exist 2 numbers in the tree whose sum is sum.
  • This problem is a variant of the two sum problem, except that the problem context is processing on a BST. The approach is generally the same: use a map to record the values of nodes that have already been visited. While traversing the tree, check whether the map contains the other half of sum.

Code

go

package leetcode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findTarget(root *TreeNode, k int) bool {
	m := make(map[int]int, 0)
	return findTargetDFS(root, k, m)
}

func findTargetDFS(root *TreeNode, k int, m map[int]int) bool {
	if root == nil {
		return false
	}
	if _, ok := m[k-root.Val]; ok {
		return ok
	}
	m[root.Val]++
	return findTargetDFS(root.Left, k, m) || findTargetDFS(root.Right, k, m)
}