首页 > 其他 > 详细

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

时间:2021-08-25 08:34:50      阅读:69      评论:0      收藏:0      [点我收藏+]

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

技术分享图片

Input: root = [5,3,6,2,4,null,7], k = 9
Output: true

Example 2:

技术分享图片

Input: root = [5,3,6,2,4,null,7], k = 28
Output: false

Example 3:

Input: root = [2,1,3], k = 4
Output: true

Example 4:

Input: root = [2,1,3], k = 1
Output: false

Example 5:

Input: root = [2,1,3], k = 3
Output: true

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -104 <= Node.val <= 104
  • root is guaranteed to be a valid binary search tree.
  • -105 <= k <= 105

两数之和 IV - 输入 BST。

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

这道题不难,这里我提供 BFS 和 DFS 两种做法,两种做法时间空间复杂度都一样。这道题其实还是找两数之和,无非是在一棵树里找。因为遍历的是树所以我们不能排序,但是我们还是可以利用 hashset 来提速。对于当前遇到的节点值 root.val,如果 hashset 里存在另一个值 K - root.val 则返回 true。遍历完整棵树还是找不到的话,则返回 false。

时间O(n)

空间O(n)

BFS实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public boolean findTarget(TreeNode root, int k) {
12         HashSet<Integer> set = new HashSet<>();
13         Queue<TreeNode> queue = new LinkedList();
14         queue.offer(root);
15         while (!queue.isEmpty()) {
16             if (queue.peek() != null) {
17                 TreeNode cur = queue.poll();
18                 if (set.contains(k - cur.val)) {
19                     return true;
20                 }
21                 set.add(cur.val);
22                 queue.add(cur.right);
23                 queue.add(cur.left);
24             } else {
25                 queue.poll();
26             }
27         }
28         return false;
29     }
30 }

 

DFS实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public boolean findTarget(TreeNode root, int k) {
12         HashSet<Integer> set = new HashSet<>();
13         return dfs(root, set, k);
14     }
15 
16     private boolean dfs(TreeNode root, HashSet<Integer> set, int k) {
17         if (root == null) return false;
18         if (set.contains(k - root.val)) {
19             return true;
20         }
21         set.add(root.val);
22         return dfs(root.left, set, k) || dfs(root.right, set, k);
23     }
24 }

 

LeetCode 题目总结

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

原文:https://www.cnblogs.com/cnoodle/p/15183042.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!