#include <stdio.h>
#include <stdlib.h>
#define TElemType int
typedef struct BitNode
{
TElemType data;
struct BitNode* lchild;
struct BitNode* rchild;
}BiTNode, *BiTree;
void CreatBiTree(BiTree T)
{
(T)->data = 1;
(T)->lchild = malloc(sizeof(BiTNode));
(T)->rchild = malloc(sizeof(BiTNode));
//1节点的左孩子2
(T)->lchild->data = 2;
(T)->lchild->lchild = (BiTree)malloc(sizeof(BiTNode));
(T)->lchild->rchild = (BiTree)malloc(sizeof(BiTNode));
//2节点的右孩子5
(T)->lchild->rchild->data = 5;
(T)->lchild->rchild->lchild = NULL;
(T)->lchild->rchild->rchild = NULL;
//1节点的右孩子3
(T)->rchild->data = 3;
(T)->rchild->lchild = (BiTree)malloc(sizeof(BiTNode));
//3节点的左孩子6
(T)->rchild->lchild->data = 6;
(T)->rchild->lchild->lchild = NULL;
(T)->rchild->lchild->rchild = NULL;
(T)->rchild->rchild = (BiTree)malloc(sizeof(BiTNode));
//3节点的右孩子7
(T)->rchild->rchild->data = 7;
(T)->rchild->rchild->lchild = NULL;
(T)->rchild->rchild->rchild = NULL;
//2节点的左孩子4
(T)->lchild->lchild->data = 4;
(T)->lchild->lchild->lchild = NULL;
(T)->lchild->lchild->rchild = NULL;
}
void printBit(BiTree elem)
{
printf("%d ", elem->data);
}
/*先序遍历*/
void pre_order_traverse(BiTree T)
{
if (T)
{
printBit(T);
pre_order_traverse(T->lchild);
pre_order_traverse(T->rchild);
}
return;
}
int top = -1;
int push(BiTree* stack, BiTree elem)
{
stack[++top] = elem;
return top;
}
int pop()
{
if (top == -1)
{
return -1;
}
top--;
return top;
}
BiTree get_top(BiTree *stack)
{
return stack[top];
}
/*先序遍历非递归算法*/
void pre_order_no_recursion(BiTree tree)
{
BiTree stack[20];
BiTree tmp;
push(stack, tree);
while (top != -1)
{
tmp = get_top(stack);
pop();
while (tmp)
{
printBit(tmp);
if (tmp->rchild)
{
push(stack, tmp->rchild);
}
tmp = tmp->lchild;
}
}
}
/*中序遍历递归算法*/
void in_order_traverse(BiTree tree)
{
if (tree)
{
in_order_traverse(tree->lchild);
printBit(tree);
in_order_traverse(tree->rchild);
}
}
/*中序遍历非递归算法*/
void in_order_traverse_no_recursion(BiTree tree)
{
BiTree stack[20];
BiTree tmp;
tmp = tree;
while (tmp || top != -1)
{
if (tmp)
{
push(stack, tmp);
tmp = tmp->lchild;
}
else
{
tmp = get_top(stack);
pop();
printBit(tmp);
tmp = tmp->rchild;
}
}
}
/*后序遍历递归算法*/
void post_order_traverse(BiTree tree)
{
if (tree)
{
post_order_traverse(tree->lchild);
post_order_traverse(tree->rchild);
printBit(tree);
}
}
int main()
{
BiTree Tree = (BiTree)malloc(sizeof(BiTNode));
CreatBiTree(Tree);
post_order_traverse(Tree);
//in_order_traverse_no_recursion(Tree);
//in_order_traverse(Tree);
//pre_order_no_recursion(Tree);
//pre_order_traverse(Tree);
return 0;
}
二叉树常用算法
最新推荐文章于 2022-08-18 23:56:07 发布