Github-145-源码 给定一个二叉树,返回它的 后序 遍历。

迭代版本,使用栈保存先前节点,最后逆序输出
/**
* Definition for a binary tree node.
* 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) {
stack<TreeNode*> stack ;
vector<int> output;
if (root == nullptr) {
return output;
}
stack.push(root);
while (!stack.empty()) {
TreeNode *node = stack.top();
stack.pop();
output.push_back(node->val);
if (node->left != nullptr) {
stack.push(node->left);
}
if (node->right != nullptr) {
stack.push(node->right);
}
}
reverse(output.begin(),output.end());
return output;
}
};