题目描述
点击打开链接 :https://www.nowcoder.com/practice/32af374b322342b68460e6fd2641dd1b?tpId=46&tqId=29035&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},
1
\
2
/
3
return[3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
/**
* 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> v;
stack<TreeNode*> s;
TreeNode* p=root;
while(p!=NULL)//遍历到左边最下边
{
s.push(p);
p=p->left;
}
while(!s.empty())
{
TreeNode* pLastVisit=p;//判断当前访问的是左节点还是右节点
p=s.top();
s.pop();
if(p->right==NULL || p->right==pLastVisit)
v.push_back(p->val);
else if(p->left==pLastVisit)
{
s.push(p);
p=p->right;
s.push(p);
while(p!=NULL)
{
if(p->left!=NULL)
{
s.push(p->left);
}
p=p->left;
}
}
}
return v;
}
};
运行结果: