资讯专栏INFORMATION COLUMN

[LeetCode] Two Sum IV - Input is a BST

snifes / 2225人阅读

Problem

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

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
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean findTarget(TreeNode root, int k) {
        Queue queue = new LinkedList();
        Set set = new HashSet<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (set.contains(k-cur.val)) return true;
            set.add(cur.val);
            if (cur.left != null) queue.offer(cur.left);
            if (cur.right != null) queue.offer(cur.right);
        }
        return false;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69362.html

相关文章

  • Leetcode PHP题解--D89 653. Two Sum IV - Input is a B

    摘要:思路思路遍历的时候,先把节点存起来,并且与每一个值相加,判断是否等于所需值。用函数判断与所求数字之差是否在数组内。否则,遍历子节点。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 D89 653. Two Sum IV - Input is a BST 题目链接 653. Two Sum IV - Input is a BST 题目分析 给定一个二叉树以及一个目标数字,判断能不能通过...

    HtmlCssJs 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • 11.leetcode Range Sum of BST

    1. Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. #### 1. 例子 Inp...

    shiweifu 评论0 收藏0
  • [LeetCode] 776. Split BST

    Problem Given a Binary Search Tree (BST) with root node root, and a target value V, split the tree into two subtrees where one subtree has nodes that are all smaller or equal to the target value, whil...

    baiy 评论0 收藏0
  • LeetCode 272 Closest Binary Tree Traversal II 解题思路

    摘要:原题网址题意在二叉搜索树当中找到离最近的个数。解题思路由于二叉搜索数的中序遍历是有序的,比如例子中的树,中序遍历为。 原题网址:https://leetcode.com/problems... Given a non-empty binary search tree and a target value, find k values in the BST that are closes...

    Youngdze 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<