[LeetCode] 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

这道题又是一道2sum的变种题,博主一直强调,平生不识TwoSum,刷尽LeetCode也枉然!只要是两数之和的题,一定要记得用哈希表来做,这道题只不过是把数组变成了一棵二叉树而已,换汤不换药,我们遍历二叉树就行,然后用一个哈希set,在递归函数函数中,如果node为空,返回false。如果k减去当前结点值在哈希set中存在,直接返回true;否则就将当前结点值加入哈希set,然后对左右子结点分别调用递归函数并且或起来返回即可,参见代码如下:

解法一:

class Solution {

public:
    bool findTarget(TreeNode* root, int k) {
        if (!root) return false;
        unordered_set<int> s;
        return helper(root, k, s);
    }
    bool helper(TreeNode* node, int k, unordered_set<int>& s) {
        if (!node) return false;
        if (s.count(k - node->val)) return true;
        s.insert(node->val);
        return helper(node->left, k, s) || helper(node->right, k, s);
    }
};

我们也可以用层序遍历来做,这样就是迭代的写法了,但是利用哈希表的精髓还是没变的,参见代码如下:

解法二:

class Solution {

public:
    bool findTarget(TreeNode* root, int k) {
        if (!root) return false;
        unordered_set<int> s;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
          auto t = q.front(); q.pop();
          if (s.count(k - t->val)) return true;
          s.insert(t->val);
          if (t->left) q.push(t->left);
          if (t->right) q.push(t->right);
        }
        return false;
    }
};

参考资料:

https://discuss.leetcode.com/topic/98440/java-c-three-simple-methods-choose-one-you-like

https://discuss.leetcode.com/topic/100110/my-c-non-recursive-solution-using-unordered_set-and-stack

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

,如需转载请自行联系原博主。

时间: 2024-08-04 14:38:06

[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树的相关文章

[LeetCode] Path Sum IV 二叉树的路径和之四

If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers. For each integer in this list: The hundreds digit represents the depth D of this node, 1 <= D <= 4. The tens digit represents the positio

[LeetCode] Trim a Binary Search Tree 修剪一棵二叉搜索树

Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies in [L, R] (R >= L). You might need to change the root of the tree, so the result should return the new root of the trimmed binary

Java实现 二叉搜索树算法(BST)

一.树 & 二叉树 树是由节点和边构成,储存元素的集合.节点分根节点.父节点和子节点的概念. 如图:树深=4; 5是根节点:同样8与3的关系是父子节点关系. 二叉树binary tree,则加了"二叉"(binary),意思是在树中作区分.每个节点至多有两个子(child),left child & right child.二叉树在很多例子中使用,比如二叉树表示算术表达式. 如图:1/8是左节点:2/3是右节点: 二.二叉搜索树 BST 顾名思义,二叉树上又加了个搜索的

[LeetCode] Map Sum Pairs 映射配对之和

Implement a MapSum class with insert, and sum methods. For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pai

[LeetCode] Sum of Square Numbers 平方数之和

Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c. Example 1: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5  Example 2: Input: 3 Output: False 这道题让我们求一个数是否能由平方数之和组成,刚开始博主没仔细看题,没有

Two Sum:两数相加

[ 问题: ] Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please no

[LeetCode]129.Sum Root to Leaf Numbers

[题目] Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 /

[LeetCode]230.Kth Smallest Element in a BST

题目 Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements. Follow up: What if the BST is modified (insert/delete operations) often and you

[LeetCode]--371. Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. Credits: Special thanks to @fujiaozhu for adding this problem and creating all test cases. 不用+号肯定想到用Java位运算 位运算中