1. Topic
Given a binary search tree, please find out the k-th largest nodes.
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 4
限制:
1 ≤ k ≤ 二叉搜索树元素个数
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
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);
}
};