#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/*
1
/ \
2 3
/ \ / \
4 # # #
/ \
# #
先序遍历 根左右
124###3##
通过先序遍历124###3##可以唯一确定一棵树
注意:
3## 说明3一定是叶子节点,也表明左右子树结束
*/
//二叉链表
typedef struct BiNode{
int data;
struct BiNode *lchild, *rchild;
}BiNode, *BiTree;
//按照给定的先序序列 建立二叉链表
BiNode * BiTree_create()
{
BiNode *tmp = NULL;
char ch;
scanf("%c", &ch);
if (ch == '#'){
return NULL;
}
else
{
tmp = (BiNode*)malloc(sizeof(BiNode));
if (tmp == NULL){
return NULL;
}
tmp->data = ch;//生成根节点
tmp->lchild = BiTree_create();//构建左子树
tmp->rchild = BiTree_create();//构建右子树
return tmp;
}
}
//先序遍历 根左右
void preOrder(BiNode *root)
{
if (root != NULL){
printf("%c", root->data);
preOrder(root->lchild);
preOrder(root->rchild);
}
}
//释放二叉链表 要按照后序遍历方式释放
void BiTree_free(BiNode *T)
{
BiNode *tmp = NULL;
if (T != NULL){
//释放左子树
if (T->lchild != NULL){
BiTree_free(T->lchild);
T->lchild = NULL;
}
//释放右子树
if (T->rchild != NULL){
BiTree_free(T->rchild);
T->rchild = NULL;
}
//释放根节点
if (T != NULL){
free(T);
T = NULL;
}
}
}
void test()
{
int nCount = 0, depthval = 0;
printf("\n 请输入如下字符: 124###3##\n");
BiNode *T = BiTree_create();
printf("\n非递归算法c++访问\n");
preOrder(T);
BiTree_free(T);
printf("树释放完毕\n");
}
void main()
{
test();
system("pause");
}