zoukankan      html  css  js  c++  java
  • [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);
        }
    };
    
  • 相关阅读:
    javaweb基础笔记(2)
    javaweb基础笔记(1)
    java基础笔记(11)
    java基础笔记(10)
    java基础笔记(9)
    洛谷 P2648 赚钱
    AcWing 走廊泼水节 题解
    对于有向图多个点到一个点的求法
    分层图的四倍经验
    洛谷 P4822 [BJWC2012]冻结
  • 原文地址:https://www.cnblogs.com/hellojamest/p/12239146.html
Copyright © 2011-2022 走看看