二叉樹的建立和先中後順序遍歷
阿新 • • 發佈:2019-01-31
二叉樹的建立
二叉樹建立問題
個人觀點
二叉樹是一對多的關係,所以在儲存結構中藉助連結串列節點進行動態儲存。首先建立節點,遞迴進行建立。
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;
}