题目描述

给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。

示例链接

解题思路

中序遍历即可,然后拿一个count变量记录,如果是要返回第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 count=0;
  15. int res;
  16. void func(TreeNode* root, int k) {
  17. if (!root)
  18. return;
  19. func(root->left, k);
  20. count++;
  21. if (count==k) {
  22. res = root->val;
  23. return;
  24. }
  25. func(root->right, k);
  26. }
  27. int kthSmallest(TreeNode* root, int k) {
  28. func(root, k);
  29. return res;
  30. }
  31. };