https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
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
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 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?
由于‘中序遍历一个二叉查找树(BST)的结果是一个有序数组’ ,因此我们只需要在遍历到第k个,返回当前元素即可。 中序遍历相关思路请查看binary-tree-traversal
- 中序遍历
/*
* @lc app=leetcode id=230 lang=javascript
*
* [230] Kth Smallest Element in a BST
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
const stack = [root];
let cur = root;
let i = 0;
function insertAllLefts(cur) {
while(cur && cur.left) {
const l = cur.left;
stack.push(l);
cur = l;
}
}
insertAllLefts(cur);
while(cur = stack.pop()) {
i++;
if (i === k) return cur.val;
const r = cur.right;
if (r) {
stack.push(r);
insertAllLefts(r);
}
}
return -1;
};
这道题有一个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?
大家可以思考一下。