Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Return all the keys in ascending order.
Example
If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].
BST + Ascending order ---> Inorder
left bound and right bound are given : k1(left) , k2(right)
Invalid area: x < k1 || x > k2
root >= left bound ----> search until reach the left bound
root <= right bound ----> search until reach the right bound
public class Solution { /** * @param root: The root of the binary search tree. * @param k1 and k2: range k1 to k2. * @return: Return all keys that k1<=key<=k2 in ascending order. */ private ArrayListresults; public ArrayList searchRange(TreeNode root, int k1, int k2) { results = new ArrayList (); helper(root, k1, k2); return results; } private void helper(TreeNode root, int k1, int k2) { if (root == null) { return; } if (root.val > k1) { helper(root.left, k1, k2); } if (root.val >= k1 && root.val <= k2) { results.add(root.val); } if (root.val < k2) { helper(root.right, k1, k2); } } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/66438.html
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...
摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...
Problem Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node c...
摘要:题目意思就是要一个个的返回当前的最小值。所以解法自然就是。我们需要找出被打乱的点并返回正确结果。然后将两个不正确的点记录下来,最后回原来正确的值。如果是叶子节点,或者只有一个子树。思想来自于的代码实现。 跳过总结请点这里:https://segmentfault.com/a/11... BST最明显的特点就是root.left.val < root.val < root.right.v...
摘要:递归法复杂度时间空间思路根据二叉树的性质,我们知道当遍历到某个根节点时,最近的那个节点要么是在子树里面,要么就是根节点本身。因为我们知道离目标数最接近的数肯定在二叉搜索的路径上。 Closest Binary Search Tree Value I Given a non-empty binary search tree and a target value, find the va...
阅读 3428·2023-04-26 01:45
阅读 2194·2021-11-23 09:51
阅读 3601·2021-10-18 13:29
阅读 3381·2021-09-07 10:12
阅读 679·2021-08-27 16:24
阅读 1740·2019-08-30 15:44
阅读 2163·2019-08-30 15:43
阅读 2917·2019-08-30 13:11