前序遍历
void f(TreeNode *r,vector<int>&a)
{
stack<int> s;
TreeNode *t=r;
while(!s.empty()||t)
{
if(t)
{
s.push(t);
a.push_back(t->val);
t=t->left;
}
else
{
t=s.top();
s.pop();
t=t->right;
}
}
}
中序遍历
void f(TreeNode *r,vector<int>&a)
{
stack<int> s;
TreeNode *t=r;
while(!s.empty()||t)
{
if(t)
{
s.push(t);
t=t->left;
}
else
{
t=s.top();
a.push_back(t->val);
s.pop();
t=t->right;
}
}
}
后序遍历
void f(TreeNode *r,vector<int>&a)
{
stack<int> s;
TreeNode *t=r;
TreeNode *pre=NULL;
while(!s.empty()||t)
{
while(t)
{
s.push(t);
t=t->left;
}
t=s.top();
if(!t->right||t->right==pre) //右节点访问过之后也要输出根节点
{
a.push_back(t->val);
pre=t;
t=NULL;
s.pop();
}
else
{
t=t->right;
}
}
}