树的相关操作

#include "stdio.h"
#include "malloc.h"


#define MAXLENGTH 128


struct Node
{
int value;
struct Node* firstChild;
struct Node* nextBrother;
};


struct Node* createNode(int value)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->value = value;
node->firstChild = NULL;
node->nextBrother = NULL;
return node;
}


struct Stack
{
struct Node* a[MAXLENGTH];
int top;
};


struct Queue
{
struct Node* a[MAXLENGTH];
int first;
int end;
int num;
};


void addChild(struct Node* node, struct Node* childNode)
{
if(node->firstChild != NULL)
{
struct Node* temp = node->firstChild;
while(temp ->nextBrother != NULL)
temp = temp->nextBrother;
temp->nextBrother = childNode;
}
else
{
node->firstChild = childNode;
}


}
void firstRoot(struct Node* root)  //递归先根遍历
{
printf("%d\n",root->value);


struct Node* temp = root->firstChild;
while(temp !=NULL)
{
firstRoot(temp);
temp = temp->nextBrother;
}
}


struct Node* pop(struct Stack* stack)
{
struct Node* node = stack->a[stack->top];
stack->top--;
return node;
}


void pull(struct Stack* stack, struct Node* node)
{
stack->a[++stack->top] = node;
}


void firstRoot_Stack(struct Node* root) //用栈来实现
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
struct Stack* child_stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->top = -1;
child_stack->top = -1;
pull(stack, root);
while(stack->top != -1 )
{
struct Node* node = pop(stack);
printf("%d\n", node->value);

struct Node* child = node->firstChild;
while(child != NULL)
{
pull(child_stack, child);
child = child->nextBrother;
}
while(child_stack->top != -1)
{
pull(stack, pop(child_stack));
}


}


}


struct Node* out(struct Queue* queue)
{
struct Node* node = queue->a[queue->first];
queue->num--;
queue->first = (queue->first + 1) % MAXLENGTH;


return node;
}


void in(struct Queue* queue, struct Node* node)
{
queue->end = (queue->end + 1) % MAXLENGTH;
queue->num++;
queue->a[queue->end] = node;
}


void layer_Root(struct Node* root) //递归层次遍历只能用队列实现
{
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->first = 0;
queue->end = -1;
queue->num = 0;
in(queue, root);
while(queue->num > 0)
{
struct Node* node = out(queue);
printf("%d\n", node->value);

struct Node* child = node->firstChild;
while(child != NULL)
{
in(queue, child);
child = child->nextBrother;
}
}


}
/*
树的结构为
1
-----
2 3 4
- -
5 6


*/




int main()
{
struct Node* first = createNode(1);
addChild(first, createNode(2));
addChild(first, createNode(3));
addChild(first, createNode(4));
addChild(first->firstChild, createNode(5));
addChild(first->firstChild->nextBrother, createNode(6));


firstRoot(first);
firstRoot_Stack(first);
layer_Root(first);
getchar();
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值