<leetcode>653.两数之和IV-输入BST——树、深度优先搜索、递归

给定一个二叉搜索树 root 和一个目标结果 k,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。

补充知识:
1、二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。二叉搜索树作为一种经典的数据结构,它既有链表的快速插入与删除操作的特点,又有数组快速查找的优势;所以应用十分广泛,例如在文件系统和数据库系统一般会采用这种数据结构进行高效率的排序与检索操作。
2、二叉搜索树的中序遍历生成的数组是升序数组,可以利用这一特性省去排序的操作。

解答一:深度优先搜索+双指针

/**
 * 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:
    void helper(TreeNode* root, vector<int> & cnt){
        if(root == nullptr) return;
        cnt.emplace_back(root->val);
        helper(root->left, cnt);
        helper(root->right, cnt);
    }

    bool findTarget(TreeNode* root, int k) {
        if(!root) return false;
        vector<int> cnt;
        helper(root,cnt);
        sort(cnt.begin(), cnt.end());
        int i = 0, j = cnt.size()-1;
        while(i != j){
            if(cnt[i] + cnt[j] == k){
                return true;
            }
            else if(cnt[i] + cnt[j] > k){
                j--;
            }else if(cnt[i] + cnt[j] < k){
                i++;
            }
        }
        return false;
    }
};

解答二:哈希表+深度优先搜索(迭代)

class Solution {
public:
    unordered_set<int> cnt;
    bool findTarget(TreeNode* root, int k) {
        if(root == nullptr) 
            return false;
        if(cnt.count(k-root->val)) 
            return true;
        cnt.emplace(root->val);
        return (findTarget(root->left, k) || findTarget(root->right, k));
    }
};

解答三:中序遍历+双指针

class Solution {
public:
    void helper(TreeNode* root,vector<int> & cnt){
        if(root == nullptr) return;
        helper(root->left, cnt);
        cnt.emplace_back(root->val);
        helper(root->right, cnt);
    }
    
    bool findTarget(TreeNode* root, int k) {
        vector<int> cnt;
        helper(root, cnt);
        int i = 0, j = cnt.size() - 1;
        while(i < j){
            if(cnt[i] + cnt[j] == k){
                return true;
            }
            else if(cnt[i] + cnt[j] > k){
                j--;
            }
            else{
                i++;
            }
        }
        return false;

    }
};

推荐解答二

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值