LeetCode 145. 二叉树的后序遍历(后序遍历总结)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 145. 二叉树的后序遍历(后序遍历总结)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 題目信息
- 2. 解法
- 2.1 遞歸
- 2.2 循環(huán),必須掌握
- a. 單棧
- b. 雙棧解法
- 3. 前中后序總結(jié)
1. 題目信息
給定一個(gè)二叉樹,返回它的 后序 遍歷。
示例:輸入: [1,null,2,3] 1\2/3 輸出: [3,2,1]進(jìn)階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
2. 解法
2.1 遞歸
class Solution { public:vector<int> postorderTraversal(TreeNode* root) {vector<int> ans;preorder(root, ans);return ans;}void preorder(TreeNode* root, vector<int> &ans){if(root == NULL)return;preorder(root->left, ans);preorder(root->right, ans);ans.push_back(root->val);} };2.2 循環(huán),必須掌握
左右根
a. 單棧
- 先按照"根-右-左"的順序遍歷二叉樹(和先序遍歷有些像),
- 然后將遍歷的結(jié)果反轉(zhuǎn)過來就是“左-右-根”,也就是后序遍歷了
以下解法會(huì)破壞二叉樹
class Solution { public:vector<int> postorderTraversal(TreeNode* root) {vector<int> ans;if(root==NULL)return ans;TreeNode *cur;stack<TreeNode*> stk;stk.push(root);while(!stk.empty()){cur = stk.top();if(cur->left){stk.push(cur->left);cur->left = NULL;}else if(cur->right){stk.push(cur->right);cur->right = NULL;}else{ans.push_back(cur->val);stk.pop();}}return ans;} };b. 雙棧解法
- stk1,模仿前序遍歷的實(shí)現(xiàn)“反后序遍歷”
- stk2,保存stk1的pop元素
3. 前中后序總結(jié)
總結(jié)
以上是生活随笔為你收集整理的LeetCode 145. 二叉树的后序遍历(后序遍历总结)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 136. 只出现一次的
- 下一篇: LeetCode 21. 合并两个有序链