LC145 Binary Tree Postorder Traversal
2016-07-28 09:35
351 查看
这个题比前序遍历难在,当tmp等于NULL时,stack需要不断地弹出节点,直到检查到一个节点,它的右节点不为空而且还没有被遍历过。这个判断条件写出来还是比较难。
当然,另一种巧妙的做法是,用前序遍历(按右根左的顺序)来求得数组,然后把数组做一个翻转就行。
当然,另一种巧妙的做法是,用前序遍历(按右根左的顺序)来求得数组,然后把数组做一个翻转就行。
class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; if(root==NULL) return result; stack<TreeNode*> is; is.push(root); TreeNode* tmp = root->left; TreeNode* pre=NULL; while(!is.empty()||tmp!=NULL) { if(tmp) { is.push(tmp); tmp=tmp->left; } else { while(!is.empty()&&(is.top()->right==NULL||is.top()->right==tmp)) { tmp=is.top(); result.push_back(tmp->val); is.pop(); } if(!is.empty()) tmp=is.top()->right; else return result; } } return result; } };
相关文章推荐
- HDU-1806 Frequent values (RMQ, 最大连续值区间)
- 内网***之socks5代理(reGeorg+proxifier详细配置说明)
- Android音频系统之AudioTrack(二)
- 表达式的类型转换
- 活在当下吧
- 各种小片段
- Hibernate1
- android studio 导入eclipse项目,程序真机运行中文显示乱码
- 高速公路(freeway)
- 初步理解android的MediaScanner(1)
- 使用ArrayList对大小写字母的随机打印
- 图标素材网站
- The content of the adapter has changed but ListView did not receive a notification的解决方案
- [置顶] The beginning
- FreeRTOS高级篇10---系统节拍时钟分析
- POJ 2371 Questions and answers
- spring整合hibernate加sqlite数据库
- 判断一个数的奇偶性
- AudioTrack
- hive的更新和删除操作脚本