剑指offer62:二插搜索树的第k个节点

本文介绍了一种寻找二叉搜索树中第K大结点的方法,通过递归中序遍历的方式实现。具体步骤包括初始化计数器,进行左子树递归,更新计数器并检查是否等于K,最后对右子树进行递归。

题目描述:

给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

中序遍历

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };
10 */
11 class Solution {
12 public:
13     TreeNode* KthNodeHelper(TreeNode* pRoot, int k, int& count) {
14         if (pRoot == nullptr) {
15             return nullptr;
16         }
17         TreeNode* node = KthNodeHelper(pRoot->left, k, count);
18         if(node) return node;
19         count++;
20         if (k == count) {
21             return pRoot;
22         }
23         node = KthNodeHelper(pRoot->right, k, count);
24         if(node) return node;
25         return nullptr;
26     }
27     TreeNode* KthNode(TreeNode* pRoot, int k) {
28         if(k<=0) return nullptr;
29         int count = 0;
30         return KthNodeHelper(pRoot, k, count);
31     }
32 };

 

转载于:https://www.cnblogs.com/wxquare/p/6767793.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值