#include<iostream>
#include<stack>
#include<cstdlib>
using namespace std;
typedef struct TreeNode
{
int data;
TreeNode *lchild;
TreeNode *rchild;
}TreeNode;
void Insert(TreeNode** root,int data)
{
if((*root) == NULL)
{
(*root) = (TreeNode*)malloc(sizeof(TreeNode));
(*root)->data = data;
(*root)->lchild = (*root)->rchild = NULL;
return;
}
if((*root)->data > data)
Insert(&(*root)->lchild,data);
else
Insert(&(*root)->rchild,data);
}
void pre_print_cur(TreeNode *root)
{
if(root != NULL)
{
cout<<root->data<<" ";
pre_print_cur(root->lchild);
pre_print_cur(root->rchild);
}
}
//对于任一结点P:
//1)访问结点P,并将结点P入栈;
//2)判断结点P的左孩子是否为空,若为空,则取栈顶结点并进行出栈操作,并将栈顶结点的右孩子置为当前的结点P,循环至1);若不为空,则将P的左孩子置为当前的结点P;
//3)直到P为NULL并且栈为空,则遍历结束。
void pre_print(TreeNode *root)
{
if(root == NULL)
return;
stack<TreeNode *>st;
TreeNode *p = root;
while(!st.empty() || p != NULL)
{
while(p != NULL)
{
cout<<p->data<<" ";
st.push(p);
p = p->lchild;
}
if(!st.empty())
{
p = st.top();
st.pop();
p = p->rchild;
}
}
}
void inorder_print_cur(TreeNode *root)
{
if(root != NULL)
{
inorder_print_cur(root->lchild);
cout<<root->data<<" ";
inorder_print_cur(root->rchild);
}
}
//对于任一结点P,
//1)若其左孩子不为空,则将P入栈并将P的左孩子置为当前的P,然后对当前结点P再进行相同的处理;
//2)若其左孩子为空,则取栈顶元素并进行出栈操作,访问该栈顶结点,然后将当前的P置为栈顶结点的右孩子;
//3)直到P为NULL并且栈为空则遍历结束
void inorder_print(TreeNode *root)
{
if(root == NULL)
return;
stack<TreeNode *>st;
TreeNode *p = root;
while(!st.empty() || p != NULL)
{
while(p != NULL)
{
st.push(p);
p = p->lchild;
}
if(!st.empty())
{
p = st.top();
cout<<p->data<<" ";
st.pop();
p = p->rchild;
}
}
}
void postorder_print_cur(TreeNode *root)
{
if(root != NULL)
{
postorder_print_cur(root->lchild);
postorder_print_cur(root->rchild);
cout<<root->data<<" ";
}
}
//要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。
//如果P不存在左孩子和右孩子,则可以直接访问它;
//或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。
//若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
void postorder_print(TreeNode *root)
{
if(root == NULL)
return;
stack<TreeNode *>st;
TreeNode *cur;
TreeNode *pre = root;
st.push(root);
while(!st.empty())
{
cur = st.top();
if((cur->lchild == NULL && cur->rchild == NULL )
||((pre != NULL)&&(pre ==cur->lchild || pre ==cur->rchild )))
{
cout<<cur->data<<" ";
st.pop();
pre = cur;
}
else
{
if(cur->rchild != NULL)
st.push(cur->rchild);
if(cur->lchild != NULL)
st.push(cur->lchild);
}
}
}
int main()
{
int arr[] = {6,3,7,2,9,1,4,5,8};
int len = sizeof(arr)/sizeof(int);
TreeNode * root = NULL;
for(int i = 0 ; i < len ;i++)
Insert(&root,arr[i]);
pre_print_cur(root);
cout<<endl;
pre_print(root);
cout<<endl;
inorder_print_cur(root);
cout<<endl;
inorder_print(root);
cout<<endl;
postorder_print_cur(root);
cout<<endl;
postorder_print(root);
cout<<endl;
return 0;
}
二叉树的先中后序遍历非递归版
最新推荐文章于 2024-07-17 12:11:36 发布