题目:Given a binary tree, return the postorder traversal of its nodes' values.
后序遍历二叉树,比前序要复杂,详细见代码注释
vector<int> postorderTraversal(TreeNode *root)
{
stack<TreeNode*> stk;
vector<int>res;
if(root == NULL) return res;
TreeNode *cur=root;
TreeNode *per=root;
stk.push(root);
while(!stk.empty() )
{
cur=stk.top();
if((cur->right==NULL && cur->left ==NULL)||(cur!=NULL &&(per==cur->right || per == cur->left)))
{ //如果P不存在左节点和右节点,则可以直接访问它;或者P的左右节点都访问了才可访问
res.push_back(cur->val) ;
stk.pop();
per=cur; //保存当前节点
}
else
{
if(cur->right!=NULL)
stk.push(cur->right);
if(cur->left!=NULL)
stk.push(cur->left);
}
}
return res;
}