您的位置:首页 > 编程语言 > C语言/C++

C语言实现二叉树的DFS

2016-07-12 18:09 423 查看
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>

struct NODE                //树的结点和栈的结点合并
{
char data;
struct NODE *lchild;
struct NODE *rchild;
struct NODE *next;
};

struct POINT            //指向栈顶和栈底的结构体
{
struct NODE *top;
struct NODE *bottom;
};

struct NODE *BuildTree(void);
struct POINT *InitStack(void);
void Push(struct POINT *p, struct NODE *q);
void Pop(struct POINT *p);
bool Empty(struct POINT *p);
void DFS(struct NODE *root);

int main()
{
struct NODE *root = BuildTree();
DFS(root);

return 0;
}

struct NODE *BuildTree(void)                 //先序顺序输入
{
char val;
struct NODE *root = NULL;

scanf("%c", &val);
if (' ' == val)
{
return NULL;
}
else
{
root = (struct NODE *)malloc(sizeof(struct NODE));
if (NULL == root)
{
printf("内存申请失败!\n");
exit(-1);
}

root->data = val;
root->lchild = BuildTree();
root->rchild = BuildTree();

return root;
}
}

struct POINT *InitStack(void)
{
struct NODE *q = (struct NODE *)malloc(sizeof(struct NODE));
if (NULL == q)
{
printf("申请内存失败!\n");
exit(-1);
}

struct POINT *point = (struct POINT *)malloc(sizeof(struct POINT));
if (NULL == point)
{
printf("申请内存失败!\n");
exit(-1);
}

point->bottom = q;
point->top = q;
q->next = NULL;

return point;
}

void Push(struct POINT *p, struct NODE *q)            //第一个参数是栈  第二个参数是要压栈的元素
{
q->next = p->top;
p->top = q;
}

void Pop(struct POINT *p)
{
struct NODE *temp = p->top;
p->top = temp->next;
free(temp);
}

bool Empty(struct POINT *p)
{
if (p->top == p->bottom)
return true;
else
return false;
}

void DFS(struct NODE *root)
{
struct POINT *stack = InitStack();
struct NODE *temp;
Push(stack, root);

while ( !Empty(stack) )
{
temp = stack->top;
printf("%c  ", temp->data);

Pop(stack);

if ( temp->rchild )
{
Push(stack, temp->rchild);
}
if ( temp->lchild )
{
Push(stack, temp->lchild);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: