[leetcode] Binary Tree Postorder Traversal
来源:互联网 发布:it监控软件 编辑:程序博客网 时间:2024/06/02 02:31
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?
递归版本:
class Solution{private: std::vector<int> result;public: vector<int> postorderTraversal(TreeNode *root) { post_traver(root); return result; } void post_traver(TreeNode * p) { if(p==NULL) return;//代码太简单,无需注释吧! post_traver(p->left); post_traver(p->right); result.push_back(p->val); }};
非递归版本:
class Solution{private:std::vector<int> result;public:vector<int> postorderTraversal(TreeNode *root){stack<TreeNode *> mystack;//使用堆栈,替换函数递归if (root != NULL) mystack.push(root);while (!mystack.empty()){TreeNode * top = mystack.top();//堆栈头部if (top == NULL) continue;if (top->left != NULL){//注意不要忘记设置top->left为NULLmystack.push(top->left); top->left = NULL;continue;}if (top->right != NULL){//注意不要忘记设置top->right为NULLmystack.push(top->right); top->right = NULL;continue;}//没有左右子树就输出结果result.push_back(top->val);mystack.pop();//这个时候才pop}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
- this、类变量和类方法、抽象与封装、继承与多态
- 让你提前认识软件开发(15):程序调试的利器—日志
- 开发中的“软”与“硬”:高画质移动游戏开发之道
- Lesson_for_java_day14--java中的泛型、Comparator、Comparable
- COJ 1059 - Numeric Parity 位操作
- [leetcode] Binary Tree Postorder Traversal
- DOS 清屏指令
- HDU 2846 ac自动机 给定n个串 q个询问 问是n个串中几个串的子串
- Web 前端性能优化——控制DOM大小
- 《算法导论》笔记 第13章 13.4 删除
- hadoop的WordCount例子
- OpenCV编程->Image Watch使用
- python学习笔记-命令行参数
- Android之DatePicker和DatePickeDialog基本用法