#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<stack>
using namespace std;
struct Node
{
int data;
struct Node *left;
struct Node *right;
Node(int data)
{
this->data=data;
this->left=NULL;
this->right=NULL;
}
};
void zhongxu(Node *root)
{
if(root==NULL)
return ;
Node *p=root;
stack<Node *>s;
while(p||!s.empty())
{
while(p)
{
s.push(p);
p=p->left;
}
if(!s.empty())
{
p=s.top();
s.pop();
cout<<p->data<<" ";
p=p->right;
}
}
}
void qianxu(Node *root)
{
if(root==NULL)
return ;
Node *p=root;
stack<Node *>s;
while(p||!s.empty())
{
while(p)
{
cout<<p->data<<" ";
s.push(p);
p=p->left;
}
if(!s.empty())
{
p=s.top();
s.pop();
p=p->right;
}
}
}
void houxu(Node *root)
{
if(root==NULL)
return ;
Node *p=root;
stack<Node *>s;
s.push(p);
s.push(p);
while(!s.empty())
{
p=s.top();
s.pop();
if(!s.empty()&&p==s.top())
{
if(p->right) s.push(p->right), s.push(p->right);
if(p->left) s.push(p->left), s.push(p->left);
}
else
cout<<p->data<<" ";
}
}
int main()
{
Node *p1=new Node(4);
Node *p2=new Node(7);
Node *p3=new Node(6);
Node *p4=new Node(3);
Node *p5=new Node(2);
Node *p6=new Node(5);
Node *p7=new Node(8);
Node *p8=new Node(1);
p1->left=p2;
p1->right=p3;
p2->left=p4;
p2->right=p5;
p3->left=p6;
p3->right=p7;
p7->right=p8;
zhongxu(p1);
cout<<endl;
qianxu(p1);
cout<<endl;
houxu(p1);
cout<<endl;
}
二叉树非递归遍历 (前,中,后) c
最新推荐文章于 2024-06-03 17:15:00 发布
本文介绍了一种使用栈实现二叉树的中序、前序和后序遍历的方法,并通过具体的C++代码示例展示了如何构造二叉树及进行不同类型的遍历。
5万+

被折叠的 条评论
为什么被折叠?



