LeetCode 230. 二叉搜索树中第K小的元素(中序遍历)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 230. 二叉搜索树中第K小的元素(中序遍历)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 題目信息
- 2. 解題
- 2.1 中序遞歸
- 2.2 中序循環(huán)寫法
1. 題目信息
給定一個(gè)二叉搜索樹,編寫一個(gè)函數(shù) kthSmallest 來查找其中第 k 個(gè)最小的元素。
說明:
你可以假設(shè) k 總是有效的,1 ≤ k ≤ 二叉搜索樹元素個(gè)數(shù)。
進(jìn)階:
如果二叉搜索樹經(jīng)常被修改(插入/刪除操作)并且你需要頻繁地查找第 k 小的值,你將如何優(yōu)化 kthSmallest 函數(shù)?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
2. 解題
- 二叉搜索樹中序輸出是非降序列
2.1 中序遞歸
class Solution { public:int kthSmallest(TreeNode* root, int k) {int i = 0, ans;bool found = false;findkth(root,k,i,ans,found);return ans;}void findkth(TreeNode* &root, int &k, int &i, int &ans, bool &found){if(root == NULL || found)return;findkth(root->left,k,i,ans,found);i++;if(i == k){ans = root->val;found = true;}findkth(root->right,k,i,ans,found);} };2.2 中序循環(huán)寫法
class Solution { public:int kthSmallest(TreeNode* root, int k) {int ans,count = 0;stack<TreeNode*> stk;while(root || !stk.empty()){while(root){stk.push(root);root = root->left;}if(!stk.empty()){root = stk.top();stk.pop();if(++count == k)return root->val;root = root->right;}}return -1;} }; 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的LeetCode 230. 二叉搜索树中第K小的元素(中序遍历)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 641. 设计循环双端
- 下一篇: 算法--递归--走台阶问题(2种递归+递