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

2024-11-28 18:23:37
推荐回答(2个)
回答1:

#include
#include
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");
}

回答2:

#include
#include

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;
}