653. Two Sum IV - Input is a BST

2018/05/01 leetcode 共 727 字,约 3 分钟

Title

the problem link

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

查看树的节点中是否有两个节点的和为某一个值

Solution

//cpp:
/**
 * 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 find(TreeNode* t,unordered_set<int> &set1,int k){
        if(!t)
            return false;
        if(set1.find(k-t->val)!=set1.end()){
            return true;
        }
        set1.insert(t->val);
        return find(t->left,set1,k)||find(t->right,set1,k);
    }
    bool findTarget(TreeNode* root, int k) {
        unordered_set<int> set1;
        return find(root,set1,k);
    }
};

Search

    Table of Contents