码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-08-15 01:21:32      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:java   UNC   遍历   else   比较   var   val   example   ===   

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

标签:java   UNC   遍历   else   比较   var   val   example   ===   

原文地址:https://www.cnblogs.com/rubylouvre/p/9479045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!