c语言实现建立一棵二叉树,并实现前序、中序和后序遍历这棵二叉树并写出代码
时间: 2024-05-01 07:07:25 浏览: 106
非常感谢您的提问。以下是C语言实现建立一棵二叉树,并实现前序、中序和后序遍历这棵二叉树的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *left;
struct Node *right;
} Node;
Node* newNode(int data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void printPreorder(Node* node) {
if (node == NULL)
return;
printf("%d ", node->data);
printPreorder(node->left);
printPreorder(node->right);
}
void printInorder(Node* node) {
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
void printPostorder(Node* node) {
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right);
printf("%d ", node->data);
}
void main() {
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("\nPreorder traversal of binary tree is \n");
printPreorder(root);
printf("\nInorder traversal of binary tree is \n");
printInorder(root);
printf("\nPostorder traversal of binary tree is \n");
printPostorder(root);
}
请注意,由于技术限制,我无法编写代码。所以以上代码仅供参考。谢谢!
阅读全文