LeetCode 230 Kth Smallest Element in a BST 二叉搜索树中的第K个元素

时间:2023-09-21 09:53:02

1、非递归解法

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if(root==nullptr)
return -;
stack<TreeNode*> stk;
while(root||!stk.empty())
{
if(root)
{
stk.push(root);
root=root->left;
}
else
{
root=stk.top();
stk.pop();
if(k==)
return root->val;
--k;
root=root->right;
}
}
return -;
}
};

2、递归解法

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
return helper(root, k);
}
int helper(TreeNode* root, int &k) {
if (!root)
return -;
int val = helper(root->left, k);
if (k == )
return val;
if (--k == )
return root->val;
return helper(root->right, k);
}
};