题目描述
给定一棵二叉搜索树,请找出其中第k大的节点。

分析
逆向中序遍历二叉搜索树,使用辅助数组存储遍历节点数值,遍历k个终止递归返回节点数值大小。
代码实现以及执行结果
void inorder(struct TreeNode* root, int* nums, int* returnSize, int k){
if(!root) return;
inorder(root->right, nums, returnSize, k);
nums[(*returnSize)++] = root->val;
if(returnSize==k) return;
inorder(root->left, nums, returnSize, k);
}
int kthLargest(struct TreeNode* root, int k){
if(!root) return NULL;
int* nums = (int *)malloc(sizeof(int) * 10000);
int* returnSize = (int *)malloc(sizeof(int));
*returnSize = 0;
inorder(root, nums, returnSize, k);
return nums[k-1];
}

本文介绍了一种在二叉搜索树中查找第k大节点的算法,通过逆向中序遍历并使用辅助数组存储节点数值,当遍历到第k个节点时返回其数值。
563

被折叠的 条评论
为什么被折叠?



