653. Two Sum IV - Input is a BST

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
看的其他coder给出的答案,很详细。

方法1

Two sum问题可以转化为查找一个数值问题,Target-node.val,主要思想是使用Hashset存储二叉搜索树的节点,对BST进行遍历,当每次插入一个节点时候,判断set中是否存Target-node.val
/**
 * 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) {
        HashSet<Integer> set = new HashSet();
        return dfs(root,set,k);
        
    }
    public boolean dfs(TreeNode root, HashSet<Integer> set ,int k)
    {
        if(root == null) return false;
        if(set.contains(k - root.val)) return true;
        set.add(root.val);
        return dfs(root.left, set, k) || dfs(root.right, set, k);
    }
}

方法2

这种方法和常规的TwoSum问题类似,先得到排序的数组,恰好二叉搜索树的中序遍历就是有序的数组,使用两个指针分别指向数组的首和尾,判断nums[i]+nums[j]的和与Target的关系。
   public boolean findTarget(TreeNode root, int k) {
        List<Integer> nums = new ArrayList<>();
        inorder(root, nums);
        for(int i = 0, j = nums.size()-1; i<j;){
            if(nums.get(i) + nums.get(j) == k)return true;
            if(nums.get(i) + nums.get(j) < k)i++;
            else j--;
        }
        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 on 2017-09-26 19:05  Wanna_Go  阅读(164)  评论(0编辑  收藏  举报

导航