653. Two Sum IV - Input is a BST - Easy

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

 

先inorder traverse,再用two pointer找target sum

time: O(n)  -- inorder traverse O(n), binary search O(logn), space: O(height)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean findTarget(TreeNode root, int k) {
        List<Integer> nums = new ArrayList<>();
        inorder(root, nums);
        int l = 0, r = nums.size() - 1;
        while(l < r) {
            if(nums.get(l) + nums.get(r) == k) {
                return true;
            } else if(nums.get(l) + nums.get(r) > k) {
                r--;
            } else {
                l++;
            }
        }
        return false;
    }
    
    public void inorder(TreeNode root, List<Integer> nums) {
        if(root == null) {
            return;
        }
        inorder(root.left, nums);
        nums.add(root.val);
        inorder(root.right, nums);
    }
}

 

posted @ 2018-12-29 16:47  fatttcat  阅读(104)  评论(0编辑  收藏  举报