11. Search Range in Binary Search Tree

分手后的思念是犯贱 2022-05-27 08:39 302阅读 0赞

11. Search Range in Binary Search Tree

Description

  1. Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree.
  2. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and
  3. x is a key of given BST. Return all the keys in ascending order.

Example

  1. If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].
  2. 20
  3. / \
  4. 8 22
  5. / \
  6. 4 12

Solution

  1. import java.util.*;
  2. /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */
  3. public class Solution {
  4. List<Integer> list = new ArrayList<>();
  5. /** * @param root: param root: The root of the binary search tree * @param k1: An integer * @param k2: An integer * @return: return: Return all keys that k1<=key<=k2 in ascending order */
  6. public List<Integer> searchRange(TreeNode root, int k1, int k2) {
  7. // write your code here
  8. if(k1>k2) return list;
  9. if(root!=null){
  10. searchRange(root.left,k1,k2);
  11. if(root.val>=k1 && root.val<=k2) list.add(root.val);
  12. searchRange(root.right,k1,k2);
  13. }
  14. return list;
  15. }
  16. }

发表评论

表情:
评论列表 (有 0 条评论,302人围观)

还没有评论,来说两句吧...

相关阅读