题目
给定一棵二叉搜索树,请找出其中第 k 大的节点的值。
首先是二叉搜索,那么中序遍历为 顺序数组,因为求第k大,那么我们可以写 到中序遍历,得到的是倒叙数组。
代码
递归
class Solution {
//需要定义两个变量
int count;//用于查找第几个
int c;//保存得到k大值
public int kthLargest(TreeNode root, int k) {
if(root == null) return 0;
count = 0;
dfs(root,k);
return c;
}
public void dfs(TreeNode cur,int k){
if(cur == null) retrun;//叶子节点
dfs(cur.right);
count ++;//因为已经拿到当前值了,所先count++
if(count == k) c = cur.val; //判断
dfs(cur.left);
}
}
迭代
class Solution {
public int kthLargest(TreeNode root, int k) {
if (root == null){
return 0;
}
int count = 0;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
if(cur!=null){
stack.push(cur);
cur = cur.right;
}else{
cur = stack.pop();
count++;
if(count == k) return cur.val;
cur = cur.left;
}
}
return 0;
}
}