int res;
int k;
public int kthLargest(TreeNode root, int k) {
this.k=k;
fun(root);
return res;
}
public void fun(TreeNode root){
if (root==null){
return ;
}
fun(root.right);
if(k == 0) return;
if (--k==0){
res = root.val;
}
fun(root.left);
}
class Solution {
public int kthLargest(TreeNode root, int k) {
Stack stack = new Stack<>();
TreeNode p = root;
int ans = 0;
//右根左进行遍历
while (p != null || !stack.isEmpty()) {
if (p != null) {
stack.push(p);
p = p.right;
} else {
p = stack.pop();
//判断是否为第k大
k--;
if (k == 0) {
ans = p.val;
break ;
}
p = p.left;
}
}
return ans;
}
}
共以下 12 个回答
时间复杂度o(n),空间复杂度o(n)
int ans;
int kthLargest(TreeNode* root, int k) {
dfs(root, k);
return ans;
}
void dfs(TreeNode* root, int& k){
if(!root) return;
dfs(root->right, k);
–k;
if(k 0) {
ans = root->val;
return;
}
dfs(root->left, k);
}
第k大元素,以右中左非递归遍历找。
中序遍历后的倒数第k位即是所求
打卡
二叉树中序遍历变种,左中右 > 右中左
根据右中左便利
1、反向中序遍历,非递归