前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LintCode-11.二叉查找树中搜索区间

LintCode-11.二叉查找树中搜索区间

作者头像
悠扬前奏
发布2019-05-31 10:29:02
4810
发布2019-05-31 10:29:02
举报

题目

描述

实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。

你实现的栈将支持pushpopmin 操作,所有操作要求都在O(1)时间内完成。

样例

如下操作:push(1)pop()push(2)push(3)min()push(1)min() 返回 1,2,1

解答

思路

建立两个栈,一个保持顶端是最小的数,另一个保存剩下的数据。

代码

代码语言:javascript
复制
/**
 * 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;
 *     }
 * }
 */
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.
     */
    ArrayList<Integer> result = new ArrayList<Integer>();
    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
        // write your code here
        if(root == null) return result;
        if(root.val >= k1 && root.val <= k2){
            result.add(root.val);
            searchRange(root.left, k1, k2);
            searchRange(root.right, k1, k2);
        }
        else if(root.val < k1){
            searchRange(root.right, k1, k2);
        }
        else if(root.val > k2){
            searchRange(root.left, k1, k2);
        }
        Collections.sort(result);
        return result;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.11.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
    • 描述
      • 样例
      • 解答
        • 思路
          • 代码
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档