两数之和 IV - 输入 BST
- 解题思路:
- 受到BST使用中序遍历后会出现从小到大依次排序,同时利用这个特性,
- 可以使用for循环,再利用数组的特性找到某个数值(target-currentValue)是否存在的下标
- 同时不能出现重复
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {boolean}
*/
var findTarget = function(root, k) {
// 中序遍历
let result = [];
let inOrder = function(root){
if(!root) return;
inOrder(root.left);
result.push(root.val);
inOrder(root.right);
}
//中序遍历 得到上升数组
inOrder(root);
// 循环找到目标值
for(let i=0; i<result.length; i++){
const index = result.indexOf(k-result[i]);
if(index>-1&&index!=i){
return true;
}
}
return false;
};
复杂度分析
- 时间复杂度O(n) 遍历所有元素,再对比
- 空间复杂度O(n) 需要一个中间数组存储遍历结果
参考链接
[leetcode 653](