Problem 418
Two Sum in a BST
Easy · 10 pts · Tree, Binary Search Tree, Two Pointers, Hash Table
Problem
Given a binary search tree with distinct values and a target K, decide whether two different nodes of the tree have values that add up to K. An inorder traversal of a BST lists the values in sorted order, after which two pointers moving inward from both ends solve the problem; a hash set of the values seen so far also works.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode. The third line contains K.
Output
Print YES if two different nodes add up to K, otherwise NO.
Constraints
1 <= number of nodes <= 10000; values are distinct; -100000 <= K <= 100000
Example input
7 5 3 6 2 4 null 7 9
Example output
YES
Explanation
With K = 9 in the tree 5 / 3 6 / 2 4 _ 7, the nodes 2 and 7 (or 3 and 6, or 4 and 5) add up to 9, so the answer is YES.