# 【Leetcode】Kth Smallest Element in a BST

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.

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:

1. Try to utilize the property of a BST.
2. What if you could modify the BST node's structure?
3. The optimal runtime complexity is O(height of BST).

1、BST中序遍历的结果是对所有结点值逐渐增大的一个排列。用List保存遍历结果，返回List的第k个元素就行了。时间复杂度是O(n)，空间复杂度是O(n)。
2、中序遍历，用计数器记录当前遍历的结点个数，当遍历到k个元素的时候返回该结点的val，无需保存遍历的结点，时间复杂度O(n)，空间复杂度O(1)。
3、修改结点数据结构，在TreeNode结点加入leftCount，表示左孩子数目，根据结点的leftCount调整递归分支，它不会遍历所有结点，而是自上而下的路径，所以时间复杂度是O(height of BST)。

	public int kthSmallest(TreeNode root, int k) {
List<Integer> list = new ArrayList<Integer>();
list = inOrder(root, list);
return list.get(k - 1);
}

public List<Integer> inOrder(TreeNode p, List<Integer> order) {
if (p != null) {
order = inOrder(p.left, order);
order = inOrder(p.right, order);
}
return order;
}

	int count = 0, result;

public int kthSmallest(TreeNode root, int k) {
if (root != null) {
kthSmallest(root.left, k);
count++;
if (count == k) {
result = root.val;
}
kthSmallest(root.right, k);
}
return result;
}

class newTreeNode { // BST
newTreeNode left, right;
int val, leftCount;// 记录左孩子个数

newTreeNode(int val) {
this.val = val;
}
}
	int result;

public int kthSmallest(newTreeNode root, int k) {
if (root != null) {
if (root.leftCount + 1 == k) {
result = root.val;
} else if (root.leftCount + 1 < k) {
kthSmallest(root.right, k - (root.leftCount + 1));
} else {
kthSmallest(root.left, k);
}
}
return result;
}


#### leetcode 230: Kth Smallest Element in a BST

2015-07-07 06:14:58

#### LeetCode 230: Kth Smallest Element in a BST

2015-07-02 14:27:17

#### leetcode 230. Kth Smallest Element in a BST-递归|非递归

2016-05-24 11:17:50

#### LeetCode 230. Kth Smallest Element in a BST 解题报告

2016-02-16 15:27:50

#### LeetCode-230. Kth Smallest Element in a BST (JAVA)二叉树第k小的数字

2017-04-29 10:36:27

#### LeetCode230——Kth Smallest Element in a BST

2015-08-03 14:25:26

#### [leetcode] 378. Kth Smallest Element in a Sorted Matrix 解题报告

2016-08-20 15:43:59

#### LeetCode—378. Kth Smallest Element in a Sorted Matrix

2016-08-02 10:20:37

#### [leetcode] 378. Kth Smallest Element in a Sorted Matrix

2016-08-02 16:38:33

#### 【Leetcode】Kth Smallest Element in a Sorted Matrix

2016-08-01 21:54:16