Leetcode#653. 两数之和 IV - 输入 BST

1. 题目

Leetcode#653. 两数之和 IV - 输入 BST

2. 方法一

2.1. 代码

class Solution {
public:
    bool findTarget(TreeNode* root, int k) {
        //使用层次遍历
        stack<TreeNode*> tempstack;
        tempstack.push(root);
        set<int> valset;
        while(!tempstack.empty()){
            auto it=tempstack.top();
            tempstack.pop();
            if(it->left!=NULL) tempstack.push(it->left);
            if(it->right!=NULL) tempstack.push(it->right);
            if(valset.count(k-it->val))
                return true;
            valset.insert(it->val);
        }
        return false;
    }
};

2.2. 结果

Leetcode#653. 两数之和 IV - 输入 BST