二叉树的建立
二叉树建立问题
个人观点
二叉树是一对多的关系,所以在存储结构中借助链表节点进行动态存储。首先建立节点,递归进行建立。
typedef char ElemType;
typedef struct node
{
ElemType data;
struct node *lchild;
struct node *rchild;
}*BiTree, BiNode;
char str[29];
int i;
BiTree CreatTree()
{
if(str[i]==',')
{
i++;
return 0;
}
else
{
BiTree T=(BiTree)malloc(sizeof(BiNode));
T->data=str[i];
i++;
T->lchild=CreatTree();
T->rchild=CreatTree();
return T;
}
return 0;
}
先中后序便利
个人观点
在二叉树的节点中,有左右子树和根节点的缘故,分为先序遍历,中序遍历和后序遍历,递归访问每一个节点。
int TreeFront(BiTree root)
{
if(root!=NULL)
{
printf("%c", root->data);
TreeFront(root->lchild);
TreeFront(root->rchild);
}
return 0;
}
指针越界的问题
在linux系统的系统版本ubuntu上,存在指针越界问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElemType;
typedef struct node
{
ElemType data;
struct node *lchild;
struct node *rchild;
}*BiTree, BiNode;
char str[29];
int i;
BiTree CreatTree()
{
if(str[i]==',')
{
i++;
return 0;
}
else
{
BiTree T=(BiTree)malloc(sizeof(BiNode));
T->data=str[i];
i++;
T->lchild=CreatTree();
T->rchild=CreatTree();
return T;
}
return 0;
}
int TreeMod(BiTree root)
{
if(root!=NULL)
{
TreeMod(root->lchild);
printf("%c", root->data);
TreeMod(root->rchild);
}
return 0;
}
int TreeFront(BiTree root)
{
if(root!=NULL)
{
printf("%c", root->data);
TreeFront(root->lchild);
TreeFront(root->rchild);
}
return 0;
}
int TreeRear(BiTree root)
{
if(root!=NULL)
{
TreeRear(root->lchild);
TreeRear(root->rchild);
printf("%c", root->data);
}
return 0;
}
int main()
{
int n;
scanf("%d", &n);
for(int j=0; j<n; j++)
{
scanf("%s", str);
BiTree root;
i=0;
root=CreatTree();
TreeMod(root);
printf("\n");
TreeRear(root);
printf("\n");
TreeFront(root);
printf("\n");
}
return 0;
}