题目介绍
剑指 Offer 54. 二叉搜索树的第k大节点
难度简单235收藏分享切换为英文接收动态反馈
给定一棵二叉搜索树,请找出其中第 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 ≤ 二叉搜索树元素个数
解题思路
解法1
由于搜索二叉树的中序遍历就是顺序遍历,可以直接用中序遍历得到数组,然后取数组的倒数第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}
*/
var kthLargest = function(root, k) {
// 获取有节点的数量
let count_r = getCount(root.right)
if (count_r >= k)
let arr = []
function kthLargestFn(root) {
if (!root) return
kthLargestFn(root.left)
arr.push(root.val)
kthLargestFn(root.right)
}
kthLargestFn(root)
return arr[arr.length - k]
};
解法2
1.获取有节点的数量,如果右边节点的数量大于等于k值说明最大数在右边节点上面 2.如果k等于右边节点数量+1,说明最大值在根节点上面,否则就在左边节点上面
代码
function getCount(root) {
if (!root) return 0
return getCount(root.left) + getCount(root.right) + 1
}
var kthLargest = function(root, k) {
let count_r = getCount(root.right)
if (count_r >= k) return kthLargest(root.right, k)
if (count_r + 1 === k) return root.val
// count_r + 1 是右节点数量加上根节点数量
return kthLargest(root.left, k - count_r - 1)
};