剑指 Offer 54. 二叉搜索树的第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 private: 12 int cnt = 0; 13 public: 14 int kthLargest(TreeNode* root, int k) { 15 int res; 16 inOrderTraverse(root, k, res); 17 18 return res; 19 } 20 21 void inOrderTraverse(TreeNode *root, int k, int& res) { 22 if(cnt == k || root == NULL) 23 return; 24 inOrderTraverse(root->right, k, res); 25 cnt++; 26 if(cnt == k) { 27 res = root->val; 28 return; 29 } 30 inOrderTraverse(root->left, k, res); 31 32 } 33 };