Two Sum IV - Input is a BST【二叉搜索树中是否存在 “和==目标值” 的一对节点】

本文探讨了在二叉搜索树中寻找两个元素,使其和等于给定目标值的问题。提供了两种解决方案:一种利用unordered_set进行查找,另一种采用二叉搜索的方式遍历树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PROBLEM:

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

SOLVE:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        unordered_set<int> showed;    //用unordered_set做,很简单的
        return dfs(root,showed,k);
    }
private:
    bool dfs(TreeNode* root,unordered_set<int>& showed,int k){
        //判断 目标值k-根节点值val 差是否在unordered_set中存在
        if(!root)
            return false;
        if(showed.count(k-root->val))
            return true;
        showed.insert(root->val);
        return dfs(root->left,showed,k)||dfs(root->right,showed,k);
    }
};
class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        //该方法使用的是二叉搜索法
        return dfs(root, root,  k);
    }
private:
    bool dfs(TreeNode* root,  TreeNode* cur, int k){
        //对 cur 节点进行扩展,同时对当前root和cur运用一次 search 方法
        if(cur == NULL)return false;
        return search(root, cur, k - cur->val) || dfs(root, cur->left, k) || dfs(root, cur->right, k);
    }
    bool search(TreeNode* root, TreeNode *cur, int value){
        //对 root 节点进行扩展,同时判断此时的 root->val和cur->val 之和是否等于目标值(同时判断root和cur是否同一节点)
        if(root == NULL)return false;
        return (root->val == value) && (root != cur) 
            || (root->val < value) && search(root->right, cur, value) 
                || (root->val > value) && search(root->left, cur, value);
    }
};

简介:第一种方法比较好懂,直接用unordered_set来存值遍历;第二种其实就是直接遍历,写得挺好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值