【LeetCode】- Kth Smallest Element in a BST(二叉搜索樹第k小的數(shù))

1、題目描述

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?

2、問題描述:

  • 二叉搜索樹的遍歷,求第k個結(jié)點的值。

3、問題關(guān)鍵:

  • 二叉樹的中序遍歷,是從小到達排列的,所以,只需要中序遍歷到第k個就可以了。
  • 中序遍歷,第k個,如果在根結(jié)點的左邊,那么k <= 0; 如果左子樹遍歷完了k=1,那么就是返回root的值,否則遍歷右子樹。

4、C++代碼:

class Solution {
public:
    int dfs(TreeNode* root, int &k) {
        if (!root) return 0;
        int left = dfs(root->left, k);//遍歷左子樹
        if (k <= 0) return left;//如果左子樹存在,那么返回左子樹的值。
        if (--k == 0) return root->val;//如果遍歷左子樹
        return dfs(root->right, k);
    }
    int kthSmallest(TreeNode* root, int k) {
        return dfs(root, k);
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容