帮我用C语言写一个二叉树先序遍历问题
时间: 2023-06-11 21:08:22 浏览: 99
好的,下面是用 C 语言实现二叉树先序遍历的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main() {
// 构造一棵二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right->val = 4;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 先序遍历
printf("Preorder traversal: ");
preorderTraversal(root);
printf("\n");
return 0;
}
```
这里我们先定义了一个 `TreeNode` 结构体,表示二叉树节点。然后实现了 `preorderTraversal` 函数,用于递归遍历二叉树。最后在 `main` 函数中构造了一棵二叉树,并调用 `preorderTraversal` 函数进行遍历。
阅读全文