数据结构 c语言版二叉树(1) 建立一棵含有n个结点的二叉树,采用二叉链表存储;

题目:二叉树操作验证
1.实验目的
(1)掌握二叉树的逻辑结构
(2)掌握二叉树的二叉链表存储结构;
(3)掌握基于二叉链表存储的二叉树的遍历操作的实现。
2.实验内容
(1) 建立一棵含有n个结点的二叉树,采用二叉链表存储;
(2) 前序(或中序、后序)遍历该二叉树。

#include<stdio.h>
#include<stdlib.h>
typedef struct node *tree_pointer;
struct node{
char ch;
tree_pointer left_child,right_child;
};
tree_pointer root=NULL;
tree_pointer create(tree_pointer ptr)
{
char ch;
scanf("%c",&ch);
if(ch==' ')
ptr=NULL;
else{
ptr=(tree_pointer)malloc(sizeof(node));
ptr->ch=ch;
ptr->left_child=create(ptr->left_child);
ptr->right_child=create(ptr->right_child);
}
return ptr;
}
void preorder(tree_pointer ptr)
{
if(ptr){
printf("%c",ptr->ch);
preorder(ptr->left_child);
preorder(ptr->right_child);
}
}
void inorder(tree_pointer ptr)
{
if(ptr){
inorder(ptr->left_child);
printf("%c",ptr->ch);
inorder(ptr->right_child);
}
}
void postorder(tree_pointer ptr)
{
if(ptr){
postorder(ptr->left_child);
postorder(ptr->right_child);
printf("%c",ptr->ch);
}
}
void main()
{
printf("构建一个二叉树(结点数为n):\n");
root=create(root);
printf("前序遍历二叉树:\n");
preorder(root);
printf("\n");
printf("中序遍历二叉树:\n");
inorder(root);
printf("\n");
printf("后序遍历二叉树:\n");
postorder(root);
printf("\n");
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-11-27
#include <stdio.h>
#include <stdlib.h>

struct BiTreeNode
{
char data;
struct BiTreeNode *rchild;
struct BiTreeNode *lchild;
};

void Create(struct BiTreeNode *&Tnode) //先序创建2叉链表
{
char ch;
scanf("%c",&ch);
if(ch=='#')
{
Tnode=NULL;
}
else
{
Tnode=new BiTreeNode;
Tnode->data=ch;
Create(Tnode->lchild);
Create(Tnode->rchild);
}
}

void PreOrder(struct BiTreeNode *&Tnode) //先序遍历2叉链表
{
struct BiTreeNode *p;
p=Tnode;
if(Tnode)
{
printf("%c ",Tnode->data);
PreOrder(Tnode->lchild);
PreOrder(Tnode->rchild);
}
}
void InOrder(struct BiTreeNode*&Tnode)//中序遍历2叉表
{
struct BiTreeNode *p;
p=Tnode;
if(Tnode)
{
InOrder(Tnode->lchild);
printf("%c ",Tnode->data);
InOrder(Tnode->rchild);
}
}
void PostOrder(struct BiTreeNode *&Tnode)//后序遍历2叉链表
{
struct BiTreeNode *p;
p=Tnode;
if(Tnode)
{

PostOrder(Tnode->lchild);
PostOrder(Tnode->rchild);
printf("%c ",Tnode->data);
}
}

int main()
{
struct BiTreeNode *Tnode;
Create(Tnode);
PreOrder(Tnode);
printf("\n");
InOrder(Tnode);
printf("\n");
PostOrder(Tnode);
printf("\n");
return 0;
}本回答被网友采纳