/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ret;
if(0==root) return ret;
stack<TreeNode *> helpStack;
TreeNode *pNode=root;
TreeNode *pLast=0;
while(!helpStack.empty() || pNode)
{
if(pNode)
{
helpStack.push(pNode);
pNode=pNode->left;
}
else
{
if(pLast==helpStack.top()->right)
{//上次访问的结点为栈顶结点的右孩子
ret.push_back(helpStack.top()->val);
pLast=helpStack.top();
helpStack.pop();
}
else
{
pNode=helpStack.top()->right;
pLast=0;
}
}
}
return ret;
}
};
Binary Tree Postorder Traversal
最新推荐文章于 2020-08-12 15:10:13 发布