【leetcode】Kth Smallest Element in a BST
来源:互联网 发布:俄罗斯生活知乎 编辑:程序博客网 时间:2024/06/05 13:23
一、问题描述
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.
二、问题分析
结合BST的特点,很容易想到的是BST的先序遍历正好是一个有序递增序列,kth即为该序列的第k个直接get到即可。
三、Java AC代码
public int kthSmallest(TreeNode root, int k) {List<Integer> list = new ArrayList<Integer>();preOrderTraverse(root, list);return list.get(k-1);}public void preOrderTraverse(TreeNode root, List<Integer> list){if (root == null) {return ;}preOrderTraverse(root.left, list);list.add(root.val);preOrderTraverse(root.right, list);}
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
- HDOJ 1247 Hat’s Words (字典树分割单词枚举切割点)
- Spark机器学习3
- Android Context 是什么?
- nginx报 File not found 错误
- 使用VMware VSphere WebService SDK进行开发 (七)——获取数据中心、集群、主机、虚拟机的目录结构
- 【leetcode】Kth Smallest Element in a BST
- UVa 914 - Jumping Champion
- A3 NO SELECT The login is O EXAMINE The login is not saf your mail client: http://mail.163.com/dashi
- Zookeeper已经分布式环境中的假死脑裂
- hdu5563 ( Clarke and five-pointed star )
- 排序算法JAVA实现三
- 对js中的引用类型的理解(2)——Object类型
- SimpleDateFormat在jdk1.6与jdk1.7之间的差别
- linux设备树中pinctrl的配置(下)