## 1. Topic

Given a binary search tree, please find out the k-th largest nodes.

``````示例 1:

3
/ \
1   4
\
2

5
/ \
3   6
/ \
2   4
/
1

1 ≤ k ≤ 二叉搜索树元素个数
``````

Source: stay button (LeetCode)

## 2. Problem Solving

Please refer to: binary tree traversal cycle written summary

### 2.1 circulating solution

``````class Solution {
public:
int kthLargest(TreeNode* root, int k) {
//右根左降序遍历
stack<TreeNode*> s;
while(root || !s.empty())
{
while(root)
{
s.push(root);
root = root->right;
}
root = s.top();
s.pop();
k--;
if(k==0)
return root->val;
root = root->left;
}
return -1;
}
};
``````

### 2.2 recursive solution

``````class Solution {
bool found = false;
int ans;
public:
int kthLargest(TreeNode* root, int k) {
dfs(root,k);
return ans;
}

void dfs(TreeNode* root, int& k)
{
if(!root || found)
return;
dfs(root->right,k);
k--;
if(k == 0)
{
found = true;
ans = root->val;
}
dfs(root->left,k);
}
};
``````

Published 644 original articles · won praise 496 · Views 140,000 +

### Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104332968
Recommended
Ranking
Daily