方法一:BST的中序遍历
二叉搜索树重要性质:BST的中序遍历是升序排列 !
那么使用 右、根、左的中序遍历,即为降序排列! 和BFS中一样可以左右颠倒!
class Solution {
int rank=0;
int r=-1;
public int kthLargest(TreeNode root, int k) {
check(root,k);
return r;
}
void check(TreeNode root,int k){
if(root==null){
return;
}
// 左右颠倒的中序
check(root.right,k);
rank++;
if(rank==k){
r=root.val;
return;
}
check(root.left,k);
}
}
class Solution {
int rank=0;
int r=-1;
List<Integer> list=new ArrayList<>();
public int kthLargest(TreeNode root, int k) {
//BST中序是升序!
if(root==null || k<0){
return -1;
}
check(root,k);
Collections.reverse(list);
int r=-1;
for(int i=0;i<=k-1;i++){
r=list.get(i);
}
return r;
}
void check(TreeNode root,int k){
if(root==null){
return;
}
//中序是升序
check(root.left,k);
list.add(root.val);
check(root.right,k);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/89295.html