[Leetcode 145, Hard] Binary Tree Postorder Traversal
2015-07-20 09:20
459 查看
Problem:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
Analysis:
Solutions:
C++:
Python:
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?
Analysis:
Solutions:
C++:
vector<int> postorderTraversal(TreeNode* root) { vector<int> node_list; if(root == NULL) return node_list; TreeNode *p_cur = root; TreeNode *p_visited = NULL; stack<TreeNode *> node_stack; while(p_cur || !node_stack.empty()) { if(p_cur) { node_stack.push(p_cur); p_cur = p_cur->left; } else { p_cur = node_stack.top(); if(p_cur->right == NULL || p_cur->right == p_visited) { node_list.push_back(p_cur->val); p_visited = p_cur; node_stack.pop(); p_cur = NULL; } else p_cur = p_cur->right; } } return node_list; }Java:
Python:
相关文章推荐
- NumPy、SciPy 等Python包在Windows下的whl安装包下载
- 登录时记住用户名和密码的Cookie实现方法
- 调用startActivityForResult启动activity,返回当前页不响应的问题(附带activity携带参数流程)
- LeeCode-Swap Nodes in Pairs
- LeeCode-Sort Colors
- mac 进程管理
- NandFlash操作详解(一)
- 跟我一起写 Makefile(二)
- Python 摘录LinkedIn用户联系人
- JS判断浏览器类型的方法总结(IE firefox chrome opera safari)
- LeeCode-Roman to Integer
- VB .bas文件生成dll并且调用
- Quartz+Spring的集群配置
- hdu 2196 树形dp
- hdu 1010 启发式搜索+奇偶剪枝
- Hibernate对象持久化框架
- LeeCode-Remove Duplicates from Sorted List
- A Simple MVVM Example[Forward]
- Android:EditText属性大全
- Vim技巧之四大模式_可视模式