LeetCode 653. Two Sum IV - Input is a BST

本文介绍了一种在二分搜索树中查找两个节点,使得这两个节点的值之和等于给定目标值的方法。通过中序遍历将二分搜索树转化为有序数组,并采用双指针技术在O(n)时间内解决问题。

1.问题描述

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

2.算法分析

该问题与普通Two Sum的区别在于是在二分搜索树中寻找两个加数。利用二分搜索树的特性,即根结点的值不小于左子树的值,且不大于右子树的值,所以首先利用中序遍历把二分搜索树转换为一个普通的有序数组,再在有序数组中使用两个指针同时从一头一尾进行遍历。需要使用额外的空间O(n).

3.代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
void inOrder( TreeNode *root, vector<int> &vec){
    if(root == NULL) return;
    inOrder(root->left, vec);
    vec.push_back(root->val);
    inOrder(root->right, vec);
}

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        vector <int> vec;
        inOrder(root, vec);
        int i = 0, j = vec.size() - 1;
        while(i < j){
            if(vec[i] + vec[j] == k)
                return true;
            else if(vec[i] + vec[j] > k)
                j--;
            else
                i++;
        }
        return false;
        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值