会遍历,知道二叉搜索树特性就能做。
class Solution {
List<Integer> list=new ArrayList<>();
public int kthLargest(TreeNode root, int k) {
rec(root);
return list.get(list.size()-k);
}
public void rec(TreeNode root){
if(root.left!=null){
rec(root.left);
}
if(root==null){
return;
}
list.add(root.val);
if(root.right!=null){
rec(root.right);
}
}
}
第一回刷没想着优化,
这里主要记录一下优化。
- 遍历到第K大,就应该停止了,把结果拿出来。
- 用到了额外的数组空间,能不能不用
注意是第K大,所以顺序右根左;第K小是左根右
class Solution {
private int res=0,count=0;
public int kthLargest(TreeNode root, int k) {
rec(root,k);
return res;
}
public void rec(TreeNode root,int k){
if(root.right!=null){
rec(root.right,k);
}
if(++count==k){
res= root.val;
return;
}
if(root.left!=null){
rec(root.left,k);
}
}
}