用c++写一个二叉树中先序中序后序的代码实现
时间: 2024-05-02 21:19:31 浏览: 40
好的,以下是用C语言实现二叉树的先序、中序和后序遍历代码:
```c
struct node{
char data;
struct node* left;
struct node* right;
};
// 先序遍历
void preorder(struct node* root){
if(root!=NULL){
printf("%c ", root->data);
preorder(root->left);
preorder(root->right);
}
}
// 中序遍历
void inorder(struct node* root){
if(root!=NULL){
inorder(root->left);
printf("%c ", root->data);
inorder(root->right);
}
}
// 后序遍历
void postorder(struct node* root){
if(root!=NULL){
postorder(root->left);
postorder(root->right);
printf("%c ", root->data);
}
}
int main(){
// 构建二叉树
struct node* root = (struct node*)malloc(sizeof(struct node));
root->data = 'A';
root->left = (struct node*)malloc(sizeof(struct node));
root->left->data = 'B';
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct node*)malloc(sizeof(struct node));
root->right->data = 'C';
root->right->left = NULL;
root->right->right = NULL;
printf("先序遍历: ");
preorder(root);
printf("\n中序遍历: ");
inorder(root);
printf("\n后序遍历: ");
postorder(root);
return 0;
}
```
如果您需要更复杂的二叉树实现或其他辅助函数,请告诉我。
阅读全文