标签:new bst java for null add sum false als
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.
Input: 
    5
   /   3   6
 / \   2   4   7
Target = 9
Output: True
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
class Solution {
    ArrayList<Integer> list = new ArrayList<>();
    public boolean findTarget(TreeNode root, int k) {
        if(root == null)
            return false;
        transfer(root);
        int i = 0;
        int j = list.size()-1;
        if(list.get(j)*2 < k)
            return false;
        if(list.get(i)*2 > k)
            return false;
        while(i<j){
            int sum = list.get(i)+list.get(j);
            if(sum==k)
                return true;
            else if(sum<k){
                i++;
            }else{
                j--;
            }
        }
        return false;
    }
    public void transfer(TreeNode root){
        if(root == null)
            return ;
        transfer(root.left);
        list.add(root.val);
        transfer(root.right);
    }
}leetcode 653. Two Sum IV - Input is a BST
标签:new bst java for null add sum false als
原文地址:https://www.cnblogs.com/clnsx/p/12240892.html