题目:
很简单。反向中序遍历然后提前退出就可以得到答案了。
不过这道题我为了加深我非递归中序遍历的印象,使用了正向中序遍历迭代的方式:
C++代码附带测试:
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x),left(nullptr),right(nullptr){}
};
TreeNode* insert(TreeNode* root,int x){
if(root==nullptr){
root = new TreeNode(x);
return root;
}
if(x>root->val){
root->right = insert(root->right,x);
}else{
root->left = insert(root->left,x);
}
return root;
}
TreeNode* createTree(vector<int> arr){
TreeNode *root = new TreeNode(arr[0]);
for(int i=1;i<arr.size();i++){
root = insert(root,arr[i]);
}
return root;
}
int inorder(TreeNode* root){
TreeNode* p = root;
stack<TreeNode*> store;
while(!store.empty()||p){
if(p){
store.push(p);
p = p->left;
}
else{
p = store.top();
store.pop();
cout<<p->val<<" ";
p = p->right;
}
}
}
void reverseinorder(TreeNode* root){
if(root==nullptr){
return;
}
reverseinorder(root->right);
cout<<root->val<<" ";
reverseinorder(root->left);
}
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
TreeNode* p = root;
stack<TreeNode*> store;
vector<int> sup;
while(!store.empty()||p){
if(p){
store.push(p);
p = p->left;
}
else{
p = store.top();
store.pop();
sup.push_back(p->val);
p = p->right;
}
}
int n = sup.size();
int ans = n - k;
return sup[ans];
}
};
int main(){
vector<int> arr = {5,3,6,2,4,1};
TreeNode* root = createTree(arr);
inorder(root);
cout<<endl;
reverseinorder(root);
Solution solution;
cout<<solution.kthLargest(root,1)<<endl;
}