给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
方法见博客:
leetcode144二叉树前序遍历
代码:
struct Command{
string s;
TreeNode* node;
Command(string s, TreeNode* node) : s(s), node(node) {}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<Command> stack;
stack.push(Command("go", root));
while(!stack.empty()){
Command command = stack.top();
stack.pop();
if(command.s == "print")
res.push_back(command.node->val);
else{
assert(command.s == "go");
stack.push(Command("print", command.node));
if(command.node->right)
stack.push(Command("go", command.node->right));
if(command.node->left)
stack.push(Command("go", command.node->left));
}
}
return res;
}
};