【leetcode】【230】Kth Smallest Element in a BST
来源:互联网 发布:东海村核事故 知乎 编辑:程序博客网 时间:2024/05/22 12:07
一、问题描述
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.
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?
Hint:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- The optimal runtime complexity is O(height of BST).
二、问题分析
结合BST的结构,可以采用中序遍历的方式,并且通过一个count值来统计遍历的个数,时间复杂度O(logn)。
三、Java AC代码
public int kthSmallest(TreeNode root, int k) {List<Integer> list = new ArrayList<Integer>();inOrderTraverse(root, list, k);return list.get(k-1);}public void inOrderTraverse(TreeNode root, List<Integer> list, int k){if (root == null || k<=0) {return ;}inOrderTraverse(root.left, list, k--);list.add(root.val);inOrderTraverse(root.right, list, k--);}
0 0
- #leetcode#Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- Leetcode|Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- 【LeetCode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- LeetCode Kth Smallest Element in a BST
- leetcode: Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- [LeetCode] Kth Smallest Element in a BST
- [LeetCode]Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- leetcode--Kth Smallest Element in a BST
- 【leetcode】Kth Smallest Element in a BST
- [leetcode] Kth Smallest Element in a BST
- [Leetcode]Kth Smallest Element in a BST
- Leetcode: Kth Smallest Element in a BST
- 主键定义为自动增长类型
- JAVA中extend和implement的区别
- Spring MVC 原理 - DispatcherServlet调用完整过程(上)
- openstack网络架构
- Deep learning(深度学习)学习笔记1
- 【leetcode】【230】Kth Smallest Element in a BST
- 如何在Mac OS 上安装Ruby运行环境
- poj(1166)——拨钟问题
- 解析解和数值解
- 资源共享
- Android 以jar包方式共享资源注意事项
- 基于PCE的SDN演进方式
- 自己整理的东西(onenote)
- Python魔术方法