145. 二叉树的后序遍历
生活随笔
收集整理的這篇文章主要介紹了
145. 二叉树的后序遍历
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)二叉樹,返回它的 后序?遍歷。
示例:
輸入: [1,null,2,3] ?
? ?1
? ? \
? ? ?2
? ? /
? ?3?
輸出: [3,2,1]
進(jìn)階:?遞歸算法很簡(jiǎn)單,你可以通過迭代算法完成嗎?
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
解法一:
class Solution { public:vector<int> postorderTraversal(TreeNode* root) {if (!root) return {};vector<int> res;stack<TreeNode*> s{{root}};TreeNode *head = root;while (!s.empty()) {TreeNode *t = s.top();if ((!t->left && !t->right) || t->left == head || t->right == head) {res.push_back(t->val);s.pop();head = t;} else {if (t->right) s.push(t->right);if (t->left) s.push(t->left);}}return res;} };?
總結(jié)
以上是生活随笔為你收集整理的145. 二叉树的后序遍历的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Leetcode | 42】129.
- 下一篇: 暂时记一下