日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

[LeetCode] Binary Tree Postorder题解

發(fā)布時(shí)間:2025/4/16 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] Binary Tree Postorder题解 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。