c语言输出二叉树先序遍历结果的第k个结点
时间: 2023-12-14 22:03:32 浏览: 99
可以使用递归的方法实现二叉树的先序遍历,并记录遍历到的结点个数。当遍历到第k个结点时,输出该结点的值即可。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点定义
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 记录遍历到的结点个数
int count = 0;
// 先序遍历二叉树,返回第k个结点
struct TreeNode* preorder(struct TreeNode* root, int k) {
if (root == NULL) {
return NULL;
}
count++;
if (count == k) {
return root;
}
struct TreeNode* left = preorder(root->left, k);
if (left != NULL) {
return left;
}
struct TreeNode* right = preorder(root->right, k);
if (right != NULL) {
return right;
}
return NULL;
}
int main() {
// 构造二叉树
struct TreeNode* node1 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node2 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node3 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node4 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* node5 = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node1->val = 1;
node2->val = 2;
node3->val = 3;
node4->val = 4;
node5->val = 5;
node1->left = node2;
node1->right = node3;
node2->left = node4;
node2->right = NULL;
node3->left = NULL;
node3->right = node5;
node4->left = NULL;
node4->right = NULL;
node5->left = NULL;
node5->right = NULL;
// 输出第3个结点的值,预期结果为4
struct TreeNode* node = preorder(node1, 3);
printf("%d\n", node->val);
return 0;
}
```
输出结果为:
```
4
```
阅读全文