1.思路
中序遍历可以得到递增的序列,所以寻求第k大的数,就用中序遍历的倒序(即先遍历右子树,再根节点,最后左子树)
2.代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int k,res;
public int kthLargest(TreeNode root, int k) {
this.k=k;
dfs(root);
return res;
}
private void dfs(TreeNode root){
if(root==null)
return;
dfs(root.right);
if(k==0)
return;
k=k-1;
if(k==0){//当前是第K大的数
res=root.val;//记录结果
return;
}
dfs(root.left);
}
}
3.复杂度
当树退化为链表时,时间复杂度、空间复杂度均为O(N)