1. 程式人生 > >[leetcode]653. Two Sum IV - Input is a BST

[leetcode]653. Two Sum IV - Input is a BST

oar array 們的 func 通過 fun number lee inpu

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

之前想到全部為結點加上parent,然後求它們的前驅後繼,但這樣時間不夠。

然後直接通過中序遍歷,將BST 變成數組,二分求值了。

var findTarget = function(root, k) {
    var array = []
    toArray(root, array)
    var low = 0, high = array.length -1
   
    while(low < high){
        var ret = array[low] + array[high]
        var diff = ret - k;
        if(diff === 0){
            return true
        }else if(diff > 0){//值比較大
            high--
        }else {
            low++
        }
    }
    return false
    
};
function toArray(root, array){
   root.left && toArray(root.left, array)
   array[array.length ] = root.val;
   root.right && toArray(root.right, array)
}

[leetcode]653. Two Sum IV - Input is a BST