https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/
使用ArrayList
//中序遍历法
class Solution {
public int kthLargest(TreeNode root, int k) {
ArrayList<Integer> list = new ArrayList<>();
r(root,list);
return list.get(list.size()-k);
}
// 二叉树递归形式中序遍历
void r(TreeNode root, List list){
if(root == null) return ;
r(root.left,list);
list.add(root.val);
r(root.right,list);
}
}
使用栈
public int kthLargest(TreeNode root, int k) {
Stack<Integer> stack = new Stack<>();
r(root,stack);
for(int i=0;i<k-1;i++){
stack.pop();
}
return stack.pop();
}
void r(TreeNode root,Stack<Integer> stack){
if(root == null) return ;
r(root.left,stack);
stack.push(root.val);
r(root.right,stack);
}
//反中序遍历法(效率高)
//反中序遍历法
class Solution {
int count=0,num=0;
public int kthLargest(TreeNode root, int k) {
fn(root,k);
return num;
}
private void fn(TreeNode root, int k) {
if(root==null) return;
fn(root.right,k);
count++;
if(count==k){
num=root.val;
return;
}
fn(root.left,k);
}
}