做题博客链接
https://blog.csdn.net/qq_43349112/article/details/108542248
题目链接
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof/
描述
给定一棵二叉搜索树,请找出其中第k大的节点。
限制:
1 ≤ k ≤ 二叉搜索树元素个数
示例
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 4
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 4
初始代码模板
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int kthLargest(TreeNode root, int k) {
}
}
代码
首先注意题目中给的二叉搜索树的结构,是左子树比根节点小,右子树比根节点大。
所以要找第k大的节点,不应该按照正常的中序遍历,而是应该反过来,按照右、根、左的顺序,这样就是降序的遍历。
数据的保存可以用全局变量来保存,具体的解析可以去看看推荐题解。
基本就是写个中序遍历。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int num;
private int k;
public int kthLargest(TreeNode root, int k) {
this.k = k;
dfs(root);
return num;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.right);
k--;
if (k == 0) {
num = root.val;
}
if (k > 0) dfs(root.left);
}
}