653. Two Sum IV - Input is a BST

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:
    bool findTarget(TreeNode* root, int k) {
       unordered_set<int> st;
       return insertIntoMap(root, st, k); 
    }
    
    bool insertIntoMap(TreeNode* root, unordered_set<int>& st, int k){
        if(!root){
            return false;
        }
        if(st.count(k - root->val)){
            return true;
        }
        st.insert(root->val);
        return insertIntoMap(root->left, st, k) || insertIntoMap(root->right, st, k);
    }
    
};
之前想了一個方法,首先遍歷一遍二叉樹,將所有節點插入到 unordered_set中,之後再遍歷,如果unordered_set中存在 k - root->val則返回true,
發現這樣是不對的。比如二叉樹[1] k = 2就不滿足。所以需要在一邊遍歷的同時,將沒有出現過的數值插入到unordered_set中,這樣比較合理。 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章