#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
struct node
{
char data;
node* left;
node* right;
node(char a = '\0',node* p1 = NULL,node* p2 = NULL) : data(a) , left(p1) , right(p2) {}
};
void build(node* &root,char* preorder,char* inorder,int len)
{
if(preorder == NULL || inorder == NULL || len == 0)
{
return;
}
root = new node(*preorder);
char* p = inorder;
//在inorder中寻找*preorder
for( ; *p != *preorder ; ++p);
int leftLen = p - inorder;
build(root->left,preorder + 1,inorder,leftLen);
build(root->right,preorder + leftLen + 1,p + 1,len - leftLen - 1);
}
void postorder(node* root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
cout << root->data /*<< endl*/;
//delete root;
}
}
//非递归形式
void preTraverse1(node* root)
{
cout << "非递归先序遍历:";
stack<node*> stk;
stk.push(root);
while(stk.empty() == 0)
{
root = stk.top(); stk.pop();
cout << root->data;
//压栈顺寻很重要哦
if(root->right)
{
stk.push(root->right);
}
if(root->left)
{
stk.push(root->left);
}
}
cout << endl;
}
void preTraverse2(node* root)
{
cout << "非递归先序遍历:";
stack<node*> stk;
while(root || stk.empty() == 0)
{
while(root)
{
cout << root->data;
stk.push(root);
root = root->left;
}
if(stk.empty() == 0)
{
root = stk.top(); stk.pop(); //回退一层
root = root->right;
}
}
cout << endl;
}
void inorderTraverse(node* root)
{
cout << "非递归中序遍历:";
stack<node*> stk;
while(root || stk.empty() == 0)
{
while(root)
{
stk.push(root);
root = root->left;
}
if(stk.empty() == 0)
{
root = stk.top(); stk.pop();
cout << root->data;
root = root->right;
}
}
cout << endl;
}
void postTraverse(node* root)
{
cout << "非递归后序遍历:";
node* pre = NULL;
stack<node*> stk;
while(root || stk.empty() == 0)
{
while(root)
{
stk.push(root);
root = root->left;
}
if(stk.empty() == 0)
{
root = stk.top();
if(root->right == NULL || root->right == pre)
{
cout << root->data;
pre = root;
//这两句话很重要
root = NULL;
stk.pop();
}
else
{
root = root->right;
}
}
}
cout << endl;
}
void postTraverse1(node* root)
{
cout << "非递归后序遍历:";
node* pre = NULL;
stack<node*> stk;
stk.push(root);
while(stk.empty() == 0)
{
root = stk.top();
if((root->left == NULL && root->right == NULL) ||
(pre && (root->left == pre || root->right == pre))
)
{
cout << root->data;
pre = root;
stk.pop();
}
else
{
if(root->right)
{
stk.push(root->right);
}
if(root->left)
{
stk.push(root->left);
}
}
}
cout << endl;
}
int main()
{
node* root;
char preorder[30],inorder[30];
while(cin >> preorder >> inorder)
{
// cout << "先序遍历:" << preorder << endl;
// cout << "中序遍历:" << inorder << endl;
cout << "后序遍历:";
build(root,preorder,inorder,strlen(preorder));
postorder(root);
cout << endl;
//preTraverse1(root);
//preTraverse2(root);
// inorderTraverse(root);
postTraverse(root);
postTraverse1(root);
cout << endl;
}
}
二叉树的遍历非递归形式
最新推荐文章于 2024-07-17 12:11:36 发布