没想到,二叉搜索树的中序遍历就是按照顺序的,长知识了。所以通过中序遍历二叉搜索树,就可以获得按大小排列的数组,就此获得第K小的结果是很自然的,贴代码
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int kthSmallest(TreeNode* root, int k) 15 { 16 dfs(root); 17 return nodes[k-1]; 18 } 19 private: 20 int i = 0; 21 vector<int> nodes; 22 void dfs(TreeNode* root) 23 { 24 if(!root) 25 { 26 return; 27 } 28 dfs(root->left); 29 nodes.push_back(root->val); 30 dfs(root->right); 31 } 32 };