https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/
题目描述
给定一棵二叉搜索树,请找出其中第k大的节点。
输入输出样例
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
题解
题目需要求第 K
大的元素,而二叉搜索树的中序遍历 left->root->right
是呈现递增顺序的(从小到大),如果每次遍历的时候计数,那么找不到第 K
大的,只能找到第K
小的。 [1, 2, 3, 4]
脑筋急转弯:
如果我们对中序遍历稍加改变,(right->root->left
)就是递减的,这样一来就可以找到第 K
大的元素了
代码:
class Solution {
public int kthLargest(TreeNode root, int k) {
// 中序遍历 left->root->right 是递增的
// right->root->left则是递减的,需要对中序遍历做一点修改
Stack<TreeNode> stack = new Stack<TreeNode>();
int count = 0;
while(!stack.isEmpty() || root != null){
while(root != null){
stack.push(root);
root = root.right;
}
root = stack.pop();
// do something
if(++count == k)
return root.val;
root = root.left;
}
throw new IllegalArgumentException("没有第k大的节点");
}
}