#include "tree.h"
#include "link_queue.h"
#include "link_stack.h"
/*****************************/
//创建 添加 查找 删除
//前序遍历 中序遍历 后序遍历
//层次遍序
/*****************************/
//创建 递归方法
pTreeNode create_tree_1(void)
{
pTreeNode new_tree;
int val;
scanf("%d",&val);
if(val < 0)
{
return NULL;
}
else
{
new_tree = (pTreeNode)malloc(sizeof(tTreeNode));
if(NULL == new_tree)
{
printf("malloc err\r\n");
return NULL;
}
new_tree->data = val;
new_tree->left = create_tree_1();
new_tree->right = create_tree_1();
}
return new_tree;
}
//创建 递归方式
void create_tree_2(pTreeNode *tree)
{
int val;
scanf("%d",val);
if(val < 0)
{
return ;
}
else
{
(*tree) = (pTreeNode)malloc(sizeof(tTreeNode));
if(NULL == (*tree))
{
printf("malloc err");
return;
}
(*tree)->data = val;
(*tree)->left = NULL;
(*tree)->right = NULL;
create_tree_2(&((*tree)->left));
create_tree_2(&((*tree)->right));
}
}
//前序遍历 递归方式
void pre_order_traversal(pTreeNode tree)
{
if(NULL == tree)
{
return ;
}
printf("%d ",tree->data);
preorder_traversal(tree->left);
preorder_traversal(tree->right);
}
//前序遍历 非递归方式实现
void pre_order_traversal_2(pTreeNode tree)
{
pLinkStack pStack;
pTreeNode pTree;
if(NULL == tree)
{
return ;
}
pStack = creat_link_stack_3();
if(NULL == pStack)
{
return ;
}
pTree = tree;
while((NULL != pTree) || (NULL != pStack->top))
{
if(NULL != pTree)
{
printf("%d ",pTree->data);
if(NULL != pTree->right)
{
push_link_stack(pStack,pTree->right);
}
pTree = pTree->left;
}
else
{
pop_link_stack(pStack,pTree);
}
}
clear_link_stack(pStack);
}
//中序遍历 递归方式
void mid_order_traversal(pTreeNode tree)
{
if(NULL == tree)
{
return ;
}
preorder_traversal(tree->left);
printf("%d ",tree->data);
preorder_traversal(tree->right);
}
//后序遍历 递归方式
void post_order_traversal(pTreeNode tree)
{
if(NULL == tree)
{
return ;
}
preorder_traversal(tree->left);
preorder_traversal(tree->right);
printf("%d ",tree->data);
}
//层次遍序
void level_order_traversal(pTreeNode tree)
{
pLinkQueue pQueue;
pTreeNode pTree;
if(NULL == tree)
{
return ;
}
pQueue = create_link_queue_3();
if(NULL != pQueue)
{
return ;
}
pTree = tree;
while((NULL != pTree) || (NULL == pQueue->header))
{
if(NULL != pTree)
{
printf("%d ",pTree->data);
if(NULL != pTree->left)
{
into_link_queue(pQueue,pTree->left);
}
if(NULL != pTree->right)
{
into_link_queue(pQueue,pTree->right);
}
}
if(NULL != pQueue->header)
{
out_link_queue(pQueue,pTree);
}
}
free_link_queue(pQueue);
}
#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED
#ifndef NULL
#define NULL ((void *)0)
#endif // NULL
typedef struct _TREE_NODE
{
int data;
struct _TREE_NODE *left;
struct _TREE_NODE *right;
}tTreeNode,*pTreeNode;
extern pTreeNode create_tree_1(void);
extern void create_tree_2(pTreeNode *tree);
extern void pre_order_traversal(pTreeNode tree);
extern void pre_order_traversal_2(pTreeNode tree);
extern void mid_order_traversal(pTreeNode tree);
extern void post_order_traversal(pTreeNode tree);
extern void level_order_traversal(pTreeNode tree);
#endif // TREE_H_INCLUDED
其中使用的链式栈与链式队列在前面博文有贴出源码