Kth Smallest Element in a BST
题意
题目很明显,就是给定一棵二叉搜索树(BST) ,然后返回第K个最小数。对于这道题,我的方法是直接进行中序遍历,返回第k个数即可。代码如下:
代码实现
/**
* 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) {
vector<int> nodes;
inorder(root,nodes);
return nodes[k-1];
}
void inorder1(TreeNode* root,vector<int>& nodes){
if(root==NULL)
return;
stack<TreeNode*> st;
TreeNode* node = root;
while(node!=NULL){
st.push(node);
node=node->left;
}
while(!st.empty()){
TreeNode* cur = st.top();
nodes.push_back(cur->val);
st.pop();
if(cur->right!=NULL){
inorder(cur->right,nodes);
}
}
}
void inorder(TreeNode* root,vector<int>& nodes){
if(root==NULL)
return;
stack<TreeNode*> st;
TreeNode* node = root;
while(node!=NULL){
st.push(node);
node=node->left;
}
while(!st.empty()){
TreeNode* cur = st.top();
nodes.push_back(cur->val);
st.pop();
if(cur->right!=NULL){
TreeNode* temp_left = cur->right;
while(temp_left!=NULL){
st.push(temp_left);
temp_left = temp_left->left;
}
//inorder(cur->right,nodes);
}
}
}
};