#include "tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stack>
using namespace std;
stack<Node*> mystack;
stack<Node*> poststack;
//********************递归版***********************//
//void do_pre_order(Node* tree){//递归实现
// if(tree == NULL)
// return;
// printf("%d ",tree->value);
// do_pre_order(tree->left);
// do_pre_order(tree->right);
//}
//
//void do_medium_order(Node* tree){
// if(tree == NULL)
// return;
// do_pre_order(tree->left);
// printf("%d ",tree->value);
// do_pre_order(tree->right);
//}
//
//void do_post_order(Node* tree){
// if(tree == NULL)
// return;
// do_pre_order(tree->left);
// do_pre_order(tree->right);
// printf("%d ",tree->value);
//}
//********************非递归版*********************//
//void do_pre_order(Node* tree){
// if(tree == NULL)
// printf("%s","the tree is empty");
// while (tree||!mystack.empty())
// {
// while (tree)
// {
// printf("%d ",tree->value);
// mystack.push(tree);
// tree = tree->left;
// }
// tree = mystack.top();
// mystack.pop();
// tree = tree->right;
// }
//}
void do_pre_order(Node* tree){//先放入右子树,再放左子树
if(tree == NULL){
printf("%s","the tree is empty");
return;
}
mystack.push(tree);
while (!mystack.empty())
{
tree = mystack.top();
mystack.pop();
printf("%d ",tree->value);
if (tree->right)
mystack.push(tree->right);
if(tree->left)
mystack.push(tree->left);
}
}
void do_medium_order(Node* tree){
if(tree ==NULL)
printf("%s","the tree is empty");
while (tree||!mystack.empty())
{
while (tree)
{
mystack.push(tree);
tree = tree->left;
}
tree = mystack.top();//堆栈模拟递归的退回
mystack.pop();
printf("%d ",tree->value);
tree = tree->right;
}
}
//void do_post_order(Node* tree){
// if(tree ==NULL)
// printf("%s","the tree is empty");
// Node* visitflag = NULL;
// while (tree)
// {
// mystack.push(tree);
// tree = tree->left;
// }
// while (!mystack.empty())
// {
// tree = mystack.top();
// if(tree->right == NULL || tree->right == visitflag)
// {
// printf("%d ",tree->value);
// mystack.pop();
// visitflag = tree;//记录最近访问的结点
//
// }
// else
// {
// tree = tree->right;
// visitflag = tree;
// while (tree)
// {
// mystack.push(tree);
// tree = tree->left;
// }
// }
// }
//}
void do_post_order(Node* tree){//双栈法实现,因为要输出左右根,所以第二个栈先放入根,再放入右,再放入左,利用第一个堆栈来控制第一个结点的放入顺序,先左,再右再根
mystack.push(tree);
while (!mystack.empty())
{
tree = mystack.top();
mystack.pop();
poststack.push(tree);
if(tree->left)
mystack.push(tree->left);
if (tree->right)
mystack.push(tree->right);
}
while (!poststack.empty())
{
tree = poststack.top();
poststack.pop();
printf("%d ",tree->value);
}
}
第十七章经典抽象数据结构四:树的前中后序遍历
最新推荐文章于 2022-07-14 22:26:04 发布