【树】230. 二叉搜索树中第K小的元素

题目:

解答:

通过构造 BST 的中序遍历序列,则第 k-1 个元素就是第 k 小的元素。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     
13     // 中序遍历
14     void inorder(TreeNode *root, vector<int> &ret)
15     {
16         if (NULL == root)
17         {
18             return;
19         }
20         inorder(root->left, ret);
21         ret.push_back(root->val);
22         inorder(root->right, ret);
23     }
24 
25     int kthSmallest(TreeNode* root, int k) 
26     {
27         vector<int> ret;
28         inorder(root, ret);
29 
30         return ret[k-1];
31     }
32 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12818277.html