1. 题目来源
2. 题目说明
3. 题目解析
后序:左+右+根
前序:根+左+右
逆后序:根+右+左
只要会写前序,稍微改动下,打印根,让右链先入栈,取栈顶的左儿子,然后再逆置返回数组,不就后序搞定了?
友情链接:
[M二叉树] lc102. 二叉树的层序遍历(队列+bfs)
[M二叉树] lc145. 二叉树的后序遍历(栈+dfs)
[M二叉树] lc94. 二叉树的中序遍历(栈+dfs)
[M二叉树] lc144. 二叉树的前序遍历(栈+dfs)
迭代代码:
/**
* 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) {
if (!root) return {};
vector<int> res;
stack<TreeNode*> stk;
while (root || stk.size()) {
while (root) {
res.push_back(root->val);
stk.push(root);
root = root->right;
}
root = stk.top()->left;
stk.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
递归代码:
/**
* 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> res;
vector<int> postorderTraversal(TreeNode* root) {
if (!root) return {};
postorderTraversal(root->left);
postorderTraversal(root->right);
res.push_back(root->val);
return res;
}
};