[LeetCode] Binary Tree Postorder题解
Binary Tree Postorder
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
這是一道LeetCode中標(biāo)記為Hard的題。事實(shí)上如果沒有限定不使用遞歸的話,這道題是非常簡(jiǎn)單的。所以我只簡(jiǎn)單回顧一下這道題的兩種解法:遞歸和迭代。
遞歸法實(shí)現(xiàn)后序遍歷
算法復(fù)雜度為O(n)。
class Solution { public:vector<int> postorderTraversal(TreeNode* root) {vector<int> re;print(root,re);return re;}void print(TreeNode *node,vector<int> &re){if(node == NULL) return; print(node->left,re);//左 print(node->right,re);//右re.push_back(node->val);//中} };遞歸實(shí)現(xiàn)前序遍歷和后序遍歷,只要把print函數(shù)中“左右中”三行代碼改成相應(yīng)的順序即可。
迭代實(shí)現(xiàn)后序遍歷
迭代實(shí)現(xiàn)遍歷的本質(zhì)是廣度優(yōu)先搜索,思路如下:
- Create an empty stack, Push root node to the stack.
- Do following while stack is not empty.
- pop an item from the stack and print it.
- push the left child of popped item to stack.
- push the right child of popped item to stack.
- reverse the ouput.
其中,容易搞錯(cuò)的是輸出“中”后,要先push左節(jié)點(diǎn),再push右節(jié)點(diǎn)。因?yàn)閷?duì)棧來說,先進(jìn)去的左節(jié)點(diǎn)會(huì)后輸出(先進(jìn)后出,后進(jìn)先出),就實(shí)現(xiàn)了“中右左”的順序,再反轉(zhuǎn)(reverse)就得到了后續(xù)遍歷(左右中)。
算法復(fù)雜度為O(n)。
class Solution { public:vector<int> postorderTraversal(TreeNode* root) {vector<int> re;stack<TreeNode*> visit;if(root != NULL) visit.push(root);while(!visit.empty()){TreeNode *topNode = visit.top();visit.pop();//top方法只是獲取最上面的元素,所以要用pop方法彈出re.push_back(topNode->val);if(topNode->left != NULL)visit.push(topNode->left);if(topNode->right != NULL)visit.push(topNode->right);}reverse(re.begin(),re.end());return re;} };轉(zhuǎn)載于:https://www.cnblogs.com/liangf27/p/9356871.html
總結(jié)
以上是生活随笔為你收集整理的[LeetCode] Binary Tree Postorder题解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 改变文本框内容
- 下一篇: DropDownList联动