zoukankan      html  css  js  c++  java
  • LT.11.Search Range In Binary Search Tree

    http://www.lintcode.com/en/problem/search-range-in-binary-search-tree/

    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].

    20
    /
    8 22
    /
    4 12

     1 public class Solution {
     2     /**
     3      * @param root: param root: The root of the binary search tree
     4      * @param k1: An integer
     5      * @param k2: An integer
     6      * @return: return: Return all keys that k1<=key<=k2 in ascending order
     7      */
     8 
     9     private List<Integer> res;
    10     public List<Integer> searchRange(TreeNode root, int k1, int k2) {
    11         // write your code here
    12         res = new ArrayList<>();
    13         helper(root, k1, k2);
    14         return res ;
    15     }
    16 
    17     // the reason to use in order is this question ask you to keep ascending order
    18     private void helper(TreeNode root, int k1 , int k2){
    19         if (root == null) {
    20             return  ;
    21         }
    22         //branch pruning and recursive note since root == k1 or root == k2 already taken care of above
    23         // else if root < k1, there is no need to go to left! every node of left in bst < root
    24         if (root.val>k1) {
    25             //go to left
    26             helper(root.left, k1, k2) ;
    27         }
    28         //in order: note here is inclusive
    29         if (k1 <= root.val && root.val <= k2 ) {
    30             res.add(root.val);
    31         }
    32          // else if root > k2, then there is no need to go to right, every node in right > root
    33         if (root.val<k2) {
    34             //go to right
    35             helper(root.right, k1, k2);
    36         }
    37     }
    38 }
  • 相关阅读:
    idea的使用和安装破解 2019.2
    get请求和post请求的区别
    MySQL-事务
    MySQL-mysql的查询练习
    MySQL-mysql的多表查询
    CodeForces
    2018宁夏邀请赛网赛 I. Reversion Count(java练习题)
    HDU
    Codeforces Round #479 (Div. 3)解题报告
    nyoj 1274信道安全 第九届河南省赛(SPFA)
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8648374.html
Copyright © 2011-2022 走看看