面试题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 public:
12 
13     void inorder(TreeNode *root, vector<int> &ret)
14     {
15         if (root)
16         {
17             inorder(root->left, ret);
18             ret.push_back(root->val);
19             inorder(root->right, ret);
20         }
21     }
22 
23     int kthLargest(TreeNode* root, int k) 
24     {
25         vector<int> result;
26         inorder(root, result);
27 
28         return result[result.size() - k];
29 
30     }
31 };

 

posted @ 2020-05-09 19:02  梦醒潇湘  阅读(152)  评论(0)    收藏  举报