Loading

【leetcode】653. Two Sum IV - Input is a BST

  

  Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.   
  two sum 很经典,经典的题目是对一个数组进行two sum或者 three sum,排序后利用双指针检索,可以压缩搜索空间。
  类似的还有以下几道题:
 
  解题思路:
  1、递归去做,用hash_set 存储树中的树,然后进行查询是否当前遍历的结点能和之前中的任意一个树加和凑成k
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        //用一个vector存起来 然后相加 但是这样没用到搜索树的性质 中序遍历就是一个有序的表
        //用hash_set 来从所有的数值 以及是否当前做差能找到这个数
        unordered_set<int> res;
        return helper(root,res,k);                 
    }
    bool helper(TreeNode* node,unordered_set<int> &res,int k )
    {
        if(node==NULL) return false; //空了就返回false
        if(res.count(k-node->val)) return true;//找到了就终止递归
        //存储当前结点的数值
        res.insert(node->val);
        return helper(node->left, res,k) ||helper(node->right,res,k);
        
    }
};

 

posted @ 2021-11-19 21:12  aalanwyr  阅读(21)  评论(0编辑  收藏  举报