剑指offer62:二插搜索树的第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     TreeNode* KthNodeHelper(TreeNode* pRoot, int k, int& count) {
14         if (pRoot == nullptr) {
15             return nullptr;
16         }
17         TreeNode* node = KthNodeHelper(pRoot->left, k, count);
18         if(node) return node;
19         count++;
20         if (k == count) {
21             return pRoot;
22         }
23         node = KthNodeHelper(pRoot->right, k, count);
24         if(node) return node;
25         return nullptr;
26     }
27     TreeNode* KthNode(TreeNode* pRoot, int k) {
28         if(k<=0) return nullptr;
29         int count = 0;
30         return KthNodeHelper(pRoot, k, count);
31     }
32 };
原文地址:https://www.cnblogs.com/wxquare/p/6767793.html