博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
230. Kth Smallest Element in a BST
阅读量:6884 次
发布时间:2019-06-27

本文共 1495 字,大约阅读时间需要 4 分钟。

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Example 1:

Input: root = [3,1,4,null,2], k = 1   3  / \ 1   4  \   2Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3       5      / \     3   6    / \   2   4  / 1Output: 3

Follow up:

What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

难度:medium

题目:给定二叉搜索树,找出其值第K小的结点。

思路:中序遍历

Runtime: 0 ms, faster than 100.00% of Java online submissions for Kth Smallest Element in a BST.

Memory Usage: 38.9 MB, less than 19.71% of Java online submissions for Kth Smallest Element in a BST.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int kthSmallest(TreeNode root, int k) {        int[] result = {root.val};        kthSmallest(root, k, new int[1], result);                return result[0];    }        public void kthSmallest(TreeNode root, int k, int[] count, int[] result) {        if (root == null || count[0] >= k) {            return;        }        kthSmallest(root.left, k, count, result);        count[0]++;        if (count[0] == k) {            result[0] = root.val;            return;        }         kthSmallest(root.right, k, count, result);    }}

转载地址:http://penbl.baihongyu.com/

你可能感兴趣的文章
chrome浏览器下用jQuery的load函数来跨域加载页面,响应状态status为(canceled)是什么情况? JSON和JSONP,也许你会豁然开朗,含jQuery用例...
查看>>
Tomcat 配置 HTTPS双向认证
查看>>
ZOJ 3511 Cake Robbery(线段树)
查看>>
[傅里叶变换及其应用学习笔记] 二十三. 线性时不变系统的基本定义
查看>>
[New Portal]Windows Azure Virtual Machine (3) 在VM上挂载磁盘
查看>>
字体随着ProgressBar的加载而滚动
查看>>
Handler 机制再了解
查看>>
如果你是前端工程师,把你的网站或者你知道的网站加进来吧
查看>>
阿里云产品头条(2017年12月刊)
查看>>
探究SQL添加非聚集索引,性能提高几十倍之谜
查看>>
Java 如何不使用 volatile 和锁实现共享变量的同步操作
查看>>
容器监控实践—PromQL查询解析
查看>>
追踪解析 Disruptor 源码
查看>>
【剑指offer】让抽象问题具体化
查看>>
聊聊flink的AbstractNonHaServices
查看>>
搭建一个通用的脚手架
查看>>
PAT A1071
查看>>
【笔记】重学前端-winter
查看>>
windows下重装xampp并做mysql数据迁移的步骤
查看>>
Java日志组件间关系
查看>>