Binary Tree Postorder Traversal--LeetCode
来源:互联网 发布:软件服务提供商 编辑:程序博客网 时间:2024/05/18 00:13
1.题目
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?
2.题意
二叉树后序遍历
3.分析
1)递归,直接按照左、右、root的顺序放进vector即可
2)借助两个栈
s1将每两个孩子节点按照左、右的顺序进栈
则每个栈顶元素出栈时再按照root、右、左的顺序进入s2
将s2所有元素出栈到vector即可得到左、右、root的后序遍历序列
4.代码
1)递归版
class Solution {public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; postorder(result, root); return result; }private: void postorder(vector<int> &result, TreeNode *root) { if(root == nullptr) return; postorder(result, root->left); postorder(result, root->right); result.push_back(root->val); }};
2)迭代版
class Solution {public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; if(root == nullptr) return result; stack<const TreeNode*> s1; stack<const TreeNode*> s2; const TreeNode *p = root; s1.push(root); while(!s1.empty()) { p = s1.top(); s1.pop(); s2.push(p); if(p->left) s1.push(p->left); if(p->right) s1.push(p->right); } while(!s2.empty()) { p = s2.top(); s2.pop(); result.push_back(p->val); } return result; }};
阅读全文
0 0
- LeetCode Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal
- leetcode Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- LeetCode | Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode
- LeetCode - Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal -- LeetCode
- [LeetCode]Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- 练习题L1-002. 打印沙漏
- 【Linux文件目录命令】nl命令
- 【java基础】java中异常的分类、区别、表现形式、原则及注意事项!
- 八大排序算法之(五)冒泡排序
- GYM
- Binary Tree Postorder Traversal--LeetCode
- 【Linux文件目录命令】more命令
- 分治策略总结
- Eclipse打包安卓应用
- 两台电脑同用一个git账户,其公钥和私钥的配置
- [小白式机器学习(一)] logistic regression(LR)对数几率回归 / 逻辑回归 公式推导
- GYM
- 【 音视频编解码技术】 音视频同步播放原理
- 同时启动多个Tomcat