LeetCode-in-Java

653. Two Sum IV - Input is a BST

Easy

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

Example 1:

Input: root = [5,3,6,2,4,null,7], k = 9

Output: true

Example 2:

Input: root = [5,3,6,2,4,null,7], k = 28

Output: false

Constraints:

Solution

import com_github_leetcode.TreeNode;
import java.util.ArrayList;
import java.util.List;

/*
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public boolean findTarget(TreeNode root, int k) {
        if (root == null) {
            return false;
        }
        List<Integer> res = new ArrayList<>();
        inOrder(res, root);
        int i = 0;
        int j = res.size() - 1;
        while (i < j) {
            int val1 = res.get(i);
            int val2 = res.get(j);
            if (val1 + val2 == k) {
                return true;
            } else if (val1 + val2 < k) {
                i++;
            } else {
                j--;
            }
        }
        return false;
    }

    private void inOrder(List<Integer> res, TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(res, root.left);
        res.add(root.val);
        inOrder(res, root.right);
    }
}