给定一个二叉树,返回它的 后序 遍历。
示例:
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解:
while( 栈非空)
{
if( p 非空)
{
}
else
{
}
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
if(root==NULL) return result;
stack<TreeNode*> S;
S.push(root);
while(!S.empty())
{
TreeNode *p=S.top();
S.pop();
if(p!=NULL)
{
S.push(p);
S.push(NULL);
if(p->right) S.push(p->right);
if(p->left) S.push(p->left);
}
else
{
p=S.top();
S.pop();
result.push_back(p->val);
}
}
return result;
}
};