LeetCode 145. Binary Tree Postorder Traversal
Solution1:递归版答案
二叉树的后序遍历递归版是很简单的,关键是迭代版的代码既难理解又难写!但听了花花酱的视频后豁然开朗!!!
迭代版链接:https://blog.youkuaiyun.com/allenlzcoder/article/details/79837841
/**
* 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) {
vector<int> res;
my_Postordertraversal(root, res);
return res;
}
void my_Postordertraversal(TreeNode* root, vector<int>& res) {
if (!root) return;
my_Postordertraversal(root->left, res);
my_Postordertraversal(root->right, res);
res.push_back(root->val);
}
};
Solution2:迭代版答案
参考花花酱:https://zxi.mytechroad.com/blog/tree/leetcode-145-binary-tree-postorder-traversal/
看了花花酱的分析,才恍然大悟。因为二叉树的迭代版前序遍历是很容易理解的,正常的前序遍历过程是:根-左-右。花花酱稍作修改,让遍历过程为 根-右-左,则此遍历结果的翻转就是后序遍历 左-右-根的结果了。
妙哉~妙哉~妙哉啊~
/**
* 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) {
if (!root) return {};
stack<TreeNode*> Tstack;
deque<int> ans;
Tstack.push(root);
while (!Tstack.empty()) {
TreeNode *temp = Tstack.top();
Tstack.pop();
ans.push_front(temp->val);
if (temp->left) Tstack.push(temp->left);
if (temp->right) Tstack.push(temp->right);
}
return vector<int> (ans.begin(), ans.end());
}
};
C++中deque的用法
deque 双端队列。支持快速随机访问。在头尾插入删除的速度很快!
详细用法,参见官网:http://www.cplusplus.com/reference/deque/deque/?kw=deque