[leetcode] 145. Binary Tree Postorder Traversal 解题报告
来源:互联网 发布:mac自带抠图 编辑:程序博客网 时间:2024/05/21 11:09
题目链接:https://leetcode.com/problems/binary-tree-postorder-traversal/
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
思路:递归的比较简单。迭代的想了好久没想到怎么做,后来看到居然是按照先序的思路,左右子树入栈顺序相反,最后将得到后序相反的序列,然后将这个序列翻转一下就可以了,感觉这种做法也挺意外的。180题了,很快就到200题的关卡了。
两种代码如下:
递归:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> postorderTraversal(TreeNode* root) { if(!root) return result; postorderTraversal(root->left); postorderTraversal(root->right); result.push_back(root->val); return result; }private: vector<int> result;};
迭代:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> postorderTraversal(TreeNode* root) { if(!root) return result; st.push(root); while(!st.empty()) { TreeNode* tem = st.top(); st.pop(); result.push_back(tem->val); if(tem->left) st.push(tem->left); if(tem->right) st.push(tem->right); } reverse(result.begin(), result.end()); return result; }private: stack<TreeNode*> st; vector<int> result;};第二种方法参考:https://leetcode.com/discuss/66062/c-iterative-solution-0ms-with-a-stack
0 0
- [LeetCode]Binary Tree Postorder Traversal,解题报告
- LeetCode 解题报告 Binary Tree Postorder Traversal
- [leetcode] 145. Binary Tree Postorder Traversal 解题报告
- 【LeetCode】145. Binary Tree Postorder Traversal 解题报告
- [Leetcode] 145. Binary Tree Postorder Traversal 解题报告
- [leetcode]145. Binary Tree Postorder Traversal@Java解题报告
- 【LeetCode】145.Binary Tree Postorder Traversal(Hard)解题报告
- LeetCode—Binary Tree Postorder Traversal 解题报告
- leetCode解题报告之Binary Tree Postorder Traversal
- [LeetCode OJ] Binary Tree Postorder Traversal 解题报告
- LeetCode(145) Binary Tree Postorder Traversal解题报告
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal解题报告
- [leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode 解题报告 Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal 解题报告
- [LeetCode]145.Binary Tree Postorder Traversal
- Linux安装keepalived
- EAS BOS Excel导入功能
- CentOS U盘安装
- ios 本地提醒
- Educational Codeforces Round 5 B
- [leetcode] 145. Binary Tree Postorder Traversal 解题报告
- quick-cocos2d-x的热更新机制实现
- CodeForces 471C MUH and House of Cards
- JAXB的继承,解组到封送类的子类
- 上班了
- windbg memory breakpoint 内存断点
- 让py变成exe
- 移动web前端开发时注意事项
- python list中append()与extend()用法