LeetCode-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:spa

Input: 
    5
   / \
  3   6
 / \   \
2   4   7
Target = 9
Output: True

Example 2:指針

Input: 
    5
   / \
  3   6
 / \   \
2   4   7
Target = 28
Output: False

將二叉搜索樹經中序遍歷保存爲遞增數組,而後使用雙指針code

    public boolean findTarget(TreeNode root, int k) {
        List<Integer> list = new ArrayList<Integer>();
        midList(root,list);
        int left =0;
        int right =list.size()-1;
        while(left<right){
            int sum =list.get(left)+list.get(right);
            if(sum==k){
                return true;
            }
            else if(sum<k){
                left++;
            }
            else{
                right--;
            }
        }
        return false;
    }
    
    public void midList(TreeNode root,List<Integer > list){
        if(root==null){
            return;
        }
        midList(root.left,list);
        list.add(root.val);
        midList(root.right,list);
    }
相關文章
相關標籤/搜索