[路飞]_每天刷leetcode_33(二叉搜索树中第K小元素 Kth Smallest Element in a BST))

177 阅读1分钟

二叉搜索树中第K小元素(Kth Smallest Element in a BST)

LeetCode传送门 Kth Smallest Element in a BST

题目

给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。

Given the root of a binary search tree, and an integer k, return the kthk^{th} smallest value (1-indexed) of all the values of the nodes in the tree.

Example:

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

Constraints:

The number of nodes in the tree is n. 1<=k<=n<=1041 <= k <= n <= 10^4 0<=Node.val<=1040 <= Node.val <= 10^4

Follow up:

If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

解题思路

这道题我们最容易想到的就是采用中序遍历,会得到一个有序的数组,然后找到其中第k-1元素即可

代码如下

function kthSmallest(root: TreeNode | null, k: number): number {
    const res = [];
    reverseTree(root, res);
    return res[k - 1];

};
function reverseTree(root, res) {
    if (!root) return;
    // 中序遍历
    if (root.left) {
        reverseTree(root.left, res);
    }
    res.push(root.val);
    if (root.right) {
        reverseTree(root.right, res);
    }

}

也可以用迭代来实现优化

function kthSmallest(root: TreeNode | null, k: number): number {
    const stack = [];
    while(stack.length || root) {
        while(root) {
            stack.push(root);
            root = root.left;
        }
        const node = stack.pop();
        if(--k ===0) {
            return node.val;
        }
        root = node.right;
    }
    return root.val;
};

除了以上方法,我查阅了解题还有

  1. 记录子树的节点数
  2. 平衡二叉搜索树

这两种优化方法来实现,今天的解题里我们就先不展开讨论了,有兴趣的同学可以自行查阅学习。