【题目】

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?

【题意】

非递归实现兴许遍历

【思路】

维护两个栈,一个栈用来存储标记,标记对应的结点的右子树是否已经被遍历。还有一个栈存储树节点,用以模拟后序遍历。

【代码】

/**
* Definition for binary tree
* 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) {
vector<int>result;
TreeNode*node=root;
stack<TreeNode*>st;
stack<bool>st_flag; while(node){
st.push(node);
st_flag.push(false);
node=node->left;
}
while(!st.empty()){
bool status = st_flag.top();
if(!status){
//訪问右子树
st_flag.pop(); st_flag.push(true);
node = st.top();
node=node->right;
while(node){
st.push(node);
st_flag.push(false);
node=node->left;
}
}
else{
//訪问当前结点
st_flag.pop();
node = st.top(); st.pop();
result.push_back(node->val);
}
}
return result;
}
};

最新文章

  1. controller_name classify constantize model_name
  2. Windows 删除 .svn标志
  3. jira插件带ui界面和几种方式
  4. 一款基于jQuery轮播切换焦点图,可播放多张图片
  5. ubuntu1304下安装boa服务器
  6. PAT-乙级-1035. 插入与归并(25)
  7. 2016年11月2日——jQuery源码学习笔记
  8. php把文件上传到远程服务器上例子
  9. java 读取并且显示 txt 文件
  10. qcow2、raw、vmdk等镜像格式
  11. PHP提取字符串中的所有汉字
  12. java中变量赋值的理解
  13. 找到一个牛的一逼的,超简易ssm和ssh的学习网址
  14. 【Python语言】Python介绍
  15. babel-polyfill使用与性能优化
  16. limits.conf文件工作原理
  17. Bootstrap datepicker 在弹出窗体modal中不工作
  18. bootstrap collapse 无法收回
  19. IAM页面是在统一区分配的还是在混合区分配的?
  20. 【转】安全加密(一):这些MCU加密方法你都知道吗?

热门文章

  1. Docker 通俗易懂的入门
  2. Filter里面实现未登录跳转,已登录权限判断
  3. C语言实验报告二
  4. 为了防止detailsview中修改后,而girdview却没立即更新显示
  5. js-触屏滑动判断滑动方向(移动版)
  6. echarts 金字塔
  7. [笔记][FPGA]如何使用SignalTap观察wire与reg值
  8. Leetcode 数组问题3:旋转数组
  9. Windows Server 2003中报PerfDisk “无法从系统读取磁盘性能信息。
  10. iOS -- 十进制、十六进制字符串,byte,data等之间的转换