目录结构
1.题目
给定一棵二叉搜索树,请找出其中第k大的节点。
示例:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 4
限制:
1 ≤ k ≤ 二叉搜索树元素个数
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
中序遍历计数即可。
public class Offer54 {
@Test
public void test() {
TreeNode root = new TreeNode(3, new TreeNode(1, null, new TreeNode(2)), new TreeNode(4));
System.out.println(kthLargest(root, 3));
}
int K, result;
public int kthLargest(TreeNode root, int k) {
K = k;
order(root);
return result;
}
public void order(TreeNode root) {
if (root != null && K != 0) {
order(root.right);
if (--K == 0) {
result = root.val;
}
order(root.left);
}
}
}
- 时间复杂度:
- 空间复杂度: