[Leetcode]653.Two Sum IV - Input is a BST

Links: LeetCode653

Given a binary search tree and a target result, if there are two elements in BST and their sum equal to the given target result, it returns true.

Related tags: hash table

Similar find two numbers, we only need to find whether there is a k- already traversed several numbers can be in the process of traversing a binary tree.

code show as below:

python:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def findTarget(self, root: TreeNode, k: int) -> bool:
        return self.dfs(root,k,{})

    def dfs(self,root,k,hashmap):
        if not root:
            return False
        if root.val in hashmap:
            return True
        hashmap[k-root.val] = 1
        return self.dfs(root.left,k,hashmap) or self.dfs(root.right,k,hashmap)

C++:

/**
 * 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_map<int,bool> hashmap;
        return dfs(root,k,hashmap);
    }

    bool dfs(TreeNode* root,int k,unordered_map<int,bool> &hashmap){
        if(!root){
            return false;
        }
        if(hashmap.find(root->val)!=hashmap.end()){
            return true;
        }
        hashmap[k-root->val] = true;
        return dfs(root->left,k,hashmap) or dfs(root->right,k,hashmap);
    }
};

Guess you like

Origin www.cnblogs.com/hellojamest/p/12239146.html