LeetCode - 653. Two Sum IV - Input is a BST

问题 easy

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

分析

代码

/*
 * 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:
    //方法一:递归法 遍历树,速度奇慢
    unordered_map<int,int> map;
    bool findTarget(TreeNode* root, int k) {
        if(root == NULL) return false;
        if(root) 
        {
            map[root->val] = 1;
            int targetToFind = k - root->val;
            if((targetToFind != root->val) && map.find(targetToFind) != map.end()) return true;

        }
        if(root->left && findTarget(root->left,k)) return true;
        if(root->right && findTarget(root->right,k)) return true;
        return false;
    }

    //使用 迭代法 遍历树,速度很快,35ms,排名进入第一根柱子
    bool findTarget(TreeNode* root, int k) {
        unordered_map<int,int> map;
        stack<TreeNode*> stack;
        int targetToFind;
        while(root || !stack.empty())
        {
            while(root)
            {
                stack.push(root);
                root = root->left;
            }
            root = stack.top();
            targetToFind = k - root->val;
            if(map.find(targetToFind) != map.end()) return true;
            map[root->val] = 1;
            root = root->right;
            stack.pop();    //容易漏,一旦漏了,stack永不为空,死循环
        }
        return false;
    }

    //使用 迭代法 遍历树,将上述的unordered_map(没必要)换成set,32ms
    bool findTarget(TreeNode* root, int k) {
        set<int> iset;
        stack<TreeNode*> stack;
        int targetToFind;
        while(root || !stack.empty())
        {
            while(root)
            {
                stack.push(root);
                root = root->left;
            }
            root = stack.top();
            targetToFind = k - root->val;
            if(iset.find(targetToFind) != iset.end()) return true;
            iset.insert(root->val);
            root = root->right;
            stack.pop();    //容易漏,一旦漏了,stack永不为空,死循环
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值