[leetcode]653. Two Sum IV - Input is a BST
阿新 • • 發佈:2018-08-15
oar array 們的 func 通過 fun number lee inpu
然後直接通過中序遍歷,將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
之前想到全部為結點加上parent,然後求它們的前驅後繼,但這樣時間不夠。
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