#include <iostream>
#include "LINKSTACK.h"
//二叉树非递归遍历
//第一步初始化根结点为False入栈
//第二步根结点弹出为False,则左右子树为False入栈(右子树先,根结点变为true后压入栈
//第三步根结点弹出(true则不管),左子树弹出为false,则其左右子树入栈(右子树先),重复直至栈中没有元素
//为null也压入栈
//二叉树的结点
typedef struct BINARYNODE{
char ch;
struct BINARYNODE* lchild;
struct BINARYNODE* rchild;
}Binarynode;
typedef struct BITREESTACKNODE{
Linknode node;
Binarynode *root;
int flag;
}Bitreestacknode;
//创建栈中的结点
Bitreestacknode *CreateBitreestacknode(Binarynode* node,int flag){
Bitreestacknode *newnode = (Bitreestacknode*) malloc(sizeof (Bitreestacknode));
newnode->root = node;
newnode->flag = flag;
return newnode;
}
//递归遍历
void Recursion(Binarynode* root){
if(root==NULL){
return;
}
printf("%c",root->ch);
Recursion(root->lchild);
Recursion(root->rchild);
}
//非递归遍历
void NonRecursion(Binarynode* root){
//创建栈
Linkstack *stack = Initlinkstack();
//把结点扔进栈
Pushlinkstack(stack, (Linknode*)CreateBitreestacknode(root,0));//初始化
while (Sizelinkstack(stack)>0){
//先弹出栈顶元素
Bitreestacknode * node = (Bitreestacknode*)Toplinkstack(stack);
Poplinkstack(stack);
//判断弹出的结点是否为空
if(node->root==NULL){
continue;//后边不执行
}
if(node->flag==1){
printf("%c",node->root->ch);
} else{
//先序遍历
//当前结点的右结点入栈
Pushlinkstack(stack, (Linknode*)CreateBitreestacknode(node->root->rchild,0));
//当前结点的左结点入栈
Pushlinkstack(stack, (Linknode*)CreateBitreestacknode(node->root->lchild,0));//中序遍历放在最后
//当前结点入栈
node->flag=1;
Pushlinkstack(stack,(Linknode*)node);//node为binary类型
}
}
}
void Createbinarytree(){
//创建结点
Binarynode node1={'A',NULL,NULL};
Binarynode node2={'B',NULL,NULL};
Binarynode node3={'C',NULL,NULL};
Binarynode node4={'D',NULL,NULL};
Binarynode node5={'E',NULL,NULL};
Binarynode node6={'F',NULL,NULL};
Binarynode node7={'G',NULL,NULL};
Binarynode node8={'H',NULL,NULL};
//建立结点关系
node1.lchild = &node2;
node1.rchild = &node6;
node2.rchild = &node3;
node3.lchild = &node4;
node3.rchild = &node5;
node6.rchild = &node7;
node7.lchild = &node8;
//非递归打印
NonRecursion(&node1);
printf("\n");
Recursion(&node1);
}
int main(){
Createbinarytree();
return 0;
}
非递归遍历二叉树的实现
最新推荐文章于 2024-08-26 20:24:23 发布