[LeetCode] Binary Tree Postorder题解
生活随笔
收集整理的這篇文章主要介紹了
[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中標記為Hard的題。事實上如果沒有限定不使用遞歸的話,這道題是非常簡單的。所以我只簡單回顧一下這道題的兩種解法:遞歸和迭代。
遞歸法實現后序遍歷
算法復雜度為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);//中} };遞歸實現前序遍歷和后序遍歷,只要把print函數中“左右中”三行代碼改成相應的順序即可。
迭代實現后序遍歷
迭代實現遍歷的本質是廣度優先搜索,思路如下:
- 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.
其中,容易搞錯的是輸出“中”后,要先push左節點,再push右節點。因為對棧來說,先進去的左節點會后輸出(先進后出,后進先出),就實現了“中右左”的順序,再反轉(reverse)就得到了后續遍歷(左右中)。
算法復雜度為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;} };轉載于:https://www.cnblogs.com/liangf27/p/9356871.html
總結
以上是生活随笔為你收集整理的[LeetCode] Binary Tree Postorder题解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 改变文本框内容
- 下一篇: DropDownList联动