#include <iostream>
#include <stack>
#include <queue>
using namespace std;
struct Node
{
char data;
Node *lchild, *rchild;
};
void Create(Node* &root)
{
char ch;
cin >> ch;
if (ch == '#')
{
root = NULL;
}
else
{
root = new Node;
root->data = ch;
Create(root->lchild);
Create(root->rchild);
}
}
void PreOrder(Node *root) //前序和中序
{
stack<Node*> s;
while(!s.empty() || root)
{
while(root) //左子树入栈
{
//cout << root->data << " "; //前序
s.push(root);
root = root->lchild;
}
//cout << s.top()->data << " "; //中序
root = s.top()->rchild;
s.pop();
}
}
void LevelOrder(Node *root) //层序遍历
{
queue<Node*> q;
if (root != NULL)
{
q.push(root);
while(!q.empty())
{
root = q.front();
cout << root->data << " ";
q.pop();
if (root->lchild)
{
q.push(root->lchild);
}
if (root->rchild)
{
q.push(root->rchild);
}
}
}
}
void PostOrder(Node *root) //后序
{
stack<Node*> s;
Node *p, *q;
int flag;
while(!s.empty() || root)
{
while(root)
{
s.push(root);
root = root->lchild;
}
flag = 1;
p = NULL;
while(flag && !s.empty())
{
q = s.top();
if (q->rchild == p)
{
cout << q->data << " ";
s.pop();
p = q; //记录访问过节点
}
else
{
root = q->rchild;
flag = 0;
}
}
}
}
void Release(Node *root)
{
if (root != NULL)
{
Release(root->lchild);
Release(root->rchild);
delete root;
}
}
int main()
{
Node *root = NULL;
Create(root);
PreOrder(root);
LevelOrder(root);
PostOrder(root);
Release(root);
return 0;
}
二叉树非递归遍历
最新推荐文章于 2023-04-26 15:06:58 发布