请将上面的代码转换为C语言
时间: 2024-02-25 09:56:56 浏览: 137
好的,根据您的要求,我将上面的Python代码转换成C语言代码。下面是转换后的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* create_node(int val) {
TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
bool is_same_tree(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) {
return true;
} else if (!root1 || !root2) {
return false;
} else if (root1->val != root2->val) {
return false;
} else {
return is_same_tree(root1->left, root2->left) && is_same_tree(root1->right, root2->right);
}
}
TreeNode* insert_node(TreeNode* root, int val) {
if (!root) {
return create_node(val);
} else if (val < root->val) {
root->left = insert_node(root->left, val);
} else {
root->right = insert_node(root->right, val);
}
return root;
}
TreeNode* build_tree(int* nums, int n) {
TreeNode* root = NULL;
for (int i = 0; i < n; i++) {
root = insert_node(root, nums[i]);
}
return root;
}
void postorder(TreeNode* root, int* res, int* returnSize) {
if (!root) {
return;
}
postorder(root->left, res, returnSize);
postorder(root->right, res, returnSize);
res[(*returnSize)++] = root->val;
}
void levelorder(TreeNode* root, int* res, int* returnSize) {
int front = 0, rear = -1;
TreeNode* queue[1000];
if (root) {
queue[++rear] = root;
}
while (front <= rear) {
TreeNode* node = queue[front++];
res[(*returnSize)++] = node->val;
if (node->left) {
queue[++rear] = node->left;
}
if (node->right) {
queue[++rear] = node->right;
}
}
}
int main() {
int n;
scanf("%d", &n);
int nums1[1000], nums2[1000];
for (int i = 0; i < n; i++) {
scanf("%d", &nums1[i]);
}
for (int i = 0; i < n; i++) {
scanf("%d", &nums2[i]);
}
TreeNode* root1 = build_tree(nums1, n);
TreeNode* root2 = build_tree(nums2, n);
if (is_same_tree(root1, root2)) {
printf("YES\n");
int res1[1000], res2[1000];
int returnSize1 = 0, returnSize2 = 0;
postorder(root1, res1, &returnSize1);
levelorder(root1, res2, &returnSize2);
for (int i = 0; i < n; i++) {
printf("%d", res1[i]);
if (i != n - 1) {
printf(" ");
}
}
printf("\n");
for (int i = 0; i < n; i++) {
printf("%d", res2[i]);
if (i != n - 1) {
printf(" ");
}
}
printf("\n");
} else {
printf("NO\n");
}
return 0;
}
```
在C语言中,没有Python中那么方便的内置数据类型和函数,因此需要自己实现树的节点结构、插入节点、后序遍历、层序遍历等函数,代码可能会比Python代码略显繁琐。但是,C语言作为一种底层语言,运行速度更快,更加适合处理一些计算密集型的任务。
阅读全文