LeetCode 230
Kth Smallest Element in a BST
Problem Description:
题目给出一棵二叉搜索树,输出第k小的结点值。
具体的题目信息:
https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/- Solution:
- 解题思路:利用中序遍历从小到大存储结点值,直接返回数组的第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) {
if (root == NULL) return 0;
stack<TreeNode*> node;
vector<int> num;
TreeNode* p = root;
while(p || !node.empty()) {
while(p) {
node.push(p);
p = p->left;
}
p = node.top();
num.push_back(p->val);
node.pop();
p = p->right;
}
return num[k-1];
}
};