二叉树的建立以及遍历
作者:
崩溃青蛙
,
2024-08-15 22:11:52
,
所有人可见
,
阅读 5
//ABC00DE0G00F000
//abd00e00c00
#include<bits/stdc++.h>
using namespace std;
struct TreeNode
{
char val;
TreeNode *left;
TreeNode *right;
};
TreeNode* Build()
{
char c;
cin>>c;
if(c=='0') return NULL;
//先序输入
TreeNode *t=new TreeNode;
t->val=c;
t->left=Build();
t->right=Build();
return t;
}
/*
void Preorder_print2(TreeNode *p)//先序非递归输出
{
stack<TreeNode*> s;
s.push(p);
while(!s.empty())
{
TreeNode *t=s.top();
s.pop();
cout<<t->val<<' ';
if(t->right)s.push(t->right);
if(t->left)s.push(t->left);
}
}
void Preorder_print(TreeNode *p)//递归先序输出
{
if(!p) return;
cout<<p->val;
Preorder_print(p->left);
Preorder_print(p->right);
}
void Inorder_print(TreeNode *p)
{
if(!p) return;
Inorder_print(p->left);
cout<<p->val;
Inorder_print(p->right);
}
void Inorder_print2(TreeNode *p)//非递归中序输出
{
stack<TreeNode*> s;
TreeNode *t=p;
while(t||!s.empty())
{
while(t)// 把当前节点的左子节点全部压入栈
{
s.push(t);
t=t->left;
}
// 从栈中弹出一个节点计算
t=s.top();
s.pop();
cout<<t->val<<" ";
// 让当前节点指向右子节点
t=t->right;
}
}
void Postorder_print(TreeNode*p)
{
if(!p) return;
Postorder_print(p->left);
Postorder_print(p->right);
cout << p->val;
}
*/
void Postorder_print2(TreeNode*p)//后序非递归遍历:
{
stack<TreeNode*> s;
TreeNode* t=p;
TreeNode* prev=NULL;
while(t||!s.empty())
{
while(t)// t结点是非空结点将当前节点及其左节点全部入栈
{
s.push(t);
t=t->left;
}
// 如果栈顶没有右子节点或右子节点已经访问完
t=s.top();
if(!t->right||t->right==prev)
{
s.pop();
cout<<t->val<<' ';
prev=t;
t=NULL;
}
else // 有右子节点且还未访问
t=t->right;
}
}
int main()
{
/*
TreeNode* root=Build();
Preorder_print2(root);
puts(" ");
Inorder_print2(root);
puts(" ");
*/
TreeNode* root=Build();
Postorder_print2(root);
puts("");
return 0;
}