C++版 - 剑指offer 面试题63:二叉搜索树的第k个结点(二叉树中序遍历的应用) 题解

这篇博客介绍了如何在二叉搜索树中找到第k个最大的结点,通过中序遍历算法实现。在非递归的C++代码实现中,遇到编译警告,经修改后成功通过牛客网在线测评。
摘要由CSDN通过智能技术生成

面试题 63:二叉搜索树的第k个结点


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

                       

图1:一个有7个结点的二叉搜索树,如果按结点数值大小顺序输出,则第3个结点的值是4


提交网址: http://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215


分析:

C++二叉树中序遍历的结果并打印可以使用递归方法实现,具体步骤如下: 1. 如果当前结点为空,返回。 2. 递归遍历左子树。 3. 输出当前结点。 4. 递归遍历右子树。 中序遍历的最后一个结点即为二叉树的最右下角结点,可以在递归遍历时记录最后一个结点中序遍历的第n个结点可以在递归遍历时使用一个计数器来记录当前是第几个结点,并在遍历到第n个结点时输出。 以下是示例代码: ```c++ #include <iostream> using namespace std; // 二叉树结点定义 struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void inorderTraversal(TreeNode* root) { if (root == NULL) { return; } inorderTraversal(root->left); cout << root->val << " "; inorderTraversal(root->right); } TreeNode* getInorderLastNode(TreeNode* root) { if (root == NULL) { return NULL; } while (root->right != NULL) { root = root->right; } return root; } int getInorderNthNode(TreeNode* root, int n, int& count) { if (root == NULL) { return -1; } int res = getInorderNthNode(root->left, n, count); if (count == n) { return root->val; } count++; if (res != -1) { return res; } return getInorderNthNode(root->right, n, count); } int main() { // 构建一个二叉树 TreeNode* root = new TreeNode(1); root->left = new TreeNode(2); root->right = new TreeNode(3); root->left->left = new TreeNode(4); root->left->right = new TreeNode(5); // 中序遍历 inorderTraversal(root); cout << endl; // 中序遍历的最后一个结点 TreeNode* lastNode = getInorderLastNode(root); cout << lastNode->val << endl; // 中序遍历的第n个结点 int n = 3; int count = 1; int nthNode = getInorderNthNode(root, n, count); cout << nthNode << endl; return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大白技术控

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值