二叉链表的生成、递归遍历、非递归遍历

#include<iostream>
using namespace std;

#define LEN sizeof(struct node)
typedef struct node *pnode;
int n; //节点个数

struct node
{
char val;
pnode lchild;
pnode rchild;
};

//生成二叉树
pnode createBinaryTree()
{
char ch;
scanf("%c", &ch); //421##3##76##8#9##

pnode root = (pnode)malloc(LEN);

if(ch == '#'){
root = NULL;
}
else{
root->val = ch;
root->lchild = createBinaryTree();
root->rchild = createBinaryTree();
}
return root;
}

//计算二叉树的节点个数
void countTreeNum(pnode p)
{
if(p){
n ++;
countTreeNum(p->lchild);
countTreeNum(p->rchild);
}
}

//前序递归遍历
void preorder(pnode p)
{
if(p){
cout << p->val << ' ';
preorder(p->lchild);
preorder(p->rchild);
}
return ;
}

//前序非递归遍历
void preorder2(pnode p)
{
pnode stack[100];
int top = 0;
while(p || top){
while(p){ //遍历左子树
cout << p->val << ' ';
stack[++ top] = p;
p = p->lchild;
}
if(top){ //通过下一次循环中的内嵌while实现右子树遍历
p = stack[top --];
p = p->rchild;
}
}
return ;
}

//中序递归遍历
void inorder(pnode p)
{
if(p){
inorder(p->lchild);
cout << p->val << ' ';
inorder(p->rchild);
}
return;
}

//中序非递归遍历
void inorder2(pnode p)
{
pnode stack[100];
int top = 0; //栈置空
while(p || top){
while(p){ //遍历左子树
stack[++ top] = p; //根节点进栈
p = p->lchild;
}
if(top){
p = stack[top --];
cout << p->val << ' '; //打印根节点
p = p->rchild; //通过下一次循环实现右子树遍历
}
}
return ;
}

//后序递归遍历
void postorder(pnode p)
{
if(p){
postorder(p->lchild);
postorder(p->rchild);
cout << p->val << ' ';
}
return ;
}


//后序非递归遍历
typedef struct
{
pnode node;
bool left;
}stacknode;

void postorder2(pnode p)
{
stacknode stack[100];
stacknode x;
int top = 0;
while(p || top){
while(p){ //遍历左子树
x.node = p;
x.left = true; //标记为左子树
stack[++ top] = x;
p = p->lchild;
}

while(top && !stack[top].left){ //表示右子树访问完毕,所以访问根节点
//p = stack[top --].node;
//cout << p->val << ' ';
/*之前是写这两行,但是会导致最后top为0时,p非空,
所以会不断循环最外层的while(p || top)如果要写这
两行而不写下面那句的话,要采用do{}while(top);
*/
cout << stack[top --].node->val << ' ';
}

if(top){
stack[top].left = false;
p = stack[top].node;
p = p->rchild;
}
}
return ;
}

int main()
{
pnode root = createBinaryTree();
n = 0;
countTreeNum(root);
cout << "节点个数:" << n << endl;

cout << "前序遍历:" << endl;
preorder(root);
cout << endl;
preorder2(root);
cout << endl << endl;

cout << "中序遍历:" << endl;
inorder(root);
cout << endl;
inorder2(root);
cout << endl << endl;

cout << "后序遍历:" << endl;
postorder(root);
cout << endl;
postorder2(root);
cout << endl << endl;
system("pause");
}

你可能感兴趣的:(非递归)