[Leetcode]653.Two Sum IV

链接:LeetCode653

给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。

相关标签:哈希表

类似于求两数之和,我们只需要在遍历二叉树过程中寻找是否存在有数为k-已经遍历到的数即可。

代码如下:

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);
    }
};
原文地址:https://www.cnblogs.com/hellojamest/p/12239146.html