请用非递归方式实现二叉树的先序、中序和后序的遍历打印。
给定一个二叉树的根结点root,请依次返回二叉树的先序,中序和后续遍历(二维数组的形式)。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class TreeToSequence {
public:
void preorder(TreeNode* root,vector<int> &result)
{
stack<TreeNode*> s;
TreeNode *p=root;
while(p!=NULL||!s.empty())
{
while(p!=NULL)
{
s.push(p);
result.push_back(p->val);
p=p->left;
}
if(!s.empty())
{
p=s.top();
s.pop();
p=p->right;
}
}
}
void midorder(TreeNode* root,vector<int> &result)
{
stack<TreeNode*> s;
TreeNode *p=root;
while(p!=NULL||!s.empty())
{
while(p!=NULL)
{
s.push(p);
p=p->left;
}
if(!s.empty())
{
p=s.top();
result.push_back(p->val);
s.pop();
p=p->right;
}
}
}
void afterorder(TreeNode* root,vector<int> &a)
{
stack<TreeNode*> s;
TreeNode *cur=NULL;
TreeNode *pre=NULL;
s.push(root);
while(root && !s.empty())
{
cur=s.top();
if((cur->left==NULL&&cur->right==NULL)||(pre!=NULL &&(pre==cur->left||pre==cur->right)))
{
a.push_back(cur->val);
s.pop();
pre=cur;
}
else
{
if(cur->right!=NULL)
s.push(cur->right);
if(cur->left!=NULL)
s.push(cur->left);
}
}
}
vector<vector<int> > convert(TreeNode* root) {
// write code here
vector<vector<int>> vec;
vector<int> result;
preorder(root,result);
vec.push_back(result);
result.clear();
midorder(root,result);
vec.push_back(result);
result.clear();
afterorder(root,result);
vec.push_back(result);
return vec;
}
};