标签:als order back 自己 root tac cpp val nod
题型一:非递归遍历二叉树后续
struct node
{
bool isfirst;
int val;
TreeNode* left,*right;
node(int _val,bool _isfirst){
val=_val;
isfirst=_isfirst;
this->left=this->right=NULL;
}
};
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> ret;
stack<node> sta;
TreeNode* p=root;
while(sta.size()>0||p)
{
while(p)
{
node n1(p->val,false);
n1.left=p->left;
n1.right=p->right;
sta.push(n1);
p=p->left;
}
if(sta.size()>0)
{
node tmp=sta.top();
sta.pop();
if(tmp.isfirst==false)
{
tmp.isfirst=true;
sta.push(tmp);
p=tmp.right;
}
else
{
ret.push_back(tmp.val);
p=NULL;
}
}
}
return ret;
}
题型二:非递归二叉序前序遍历(中序差不多,就不写了,自己去脑补去。。。。
vector<int> preorderTraversal(TreeNode *root) {
// write your code here
vector<int> ret;
stack<TreeNode*> sta;
TreeNode* p=root;
while(sta.size()>0||p)
{
while(p)
{
sta.push(p);
ret.push_back(p->val);
p=p->left;
}
if(sta.size())
{
TreeNode* tmp=sta.top();
sta.pop();
p=tmp->right;
}
}
return ret;
}
标签:als order back 自己 root tac cpp val nod
原文地址:http://www.cnblogs.com/wuxiangli/p/7295576.html