题目
给定一棵二叉搜索树,请找出其中第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
限制:
1 ≤ k ≤ 二叉搜索树元素个数
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
- 反向中序遍历
二叉搜索树,中序遍历得到的是从小到大的顺序队列
如果,反向中序遍历,右根左,则得到的是从大到小的顺序
此时,可以记录第K大的节点的序号,到达第K大时直接退出递归
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @param {number} k* @return {number}*/const kthLargest = function (root, k) {let res = null, count = 0const helper = (root) => {if (!root) returnhelper(root.right)if (++count === k) {res = root.valreturn}helper(root.left)}helper(root)return res};
