题目要求:
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
解题代码:
//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) {}
};
struct Command {
string s; // go, print
TreeNode* node;
Command(string s, TreeNode* node): s(s), node(node) {}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) { // 后序遍历
vector<int> res;
if (root == NULL)
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;
}
};