剑指offer 二叉搜索树的第k个结点

题目:

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

代码:

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };
10 */
11 class Solution {
12 public:
13     int count = 0;
14     TreeNode* KthNode(TreeNode* pRoot, int k) {
15         if(pRoot != NULL) {
16             TreeNode* temp = KthNode(pRoot->left,k);
17             if(temp != NULL)
18                 return temp;
19             count ++;
20             if(count == k)
21                 return pRoot;
22             temp = KthNode(pRoot->right,k);
23             if(temp != NULL)
24                 return temp;
25         }
26         return NULL;
27     }
28 };

我的笔记:

  二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。所以,按照中序遍历顺序找到第k个结点就是结果。

posted @ 2020-06-15 17:46  John_yan15  阅读(143)  评论(0)    收藏  举报