leetcode Binary Tree Postorder
来源:互联网 发布:淘宝宝贝宣言怎么写 编辑:程序博客网 时间:2024/05/11 21:38
题目:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
题意:后序不让用递归遍历二叉树
思路:先root进站,取栈顶
1,一直找到最左的子节点,边找边进站,成为新的栈顶
2.判断栈顶的右子节点有没有被访问
3.如果没有,取右子节点,重复1的工作
4,如果有,按照后序遍历,既然右边都被访问了,那么肯定左边在右边之前被访问了,那么就可以访问本身节点了,然后向上走一级,把刚才访问的节点当成上一级的右子节点
代码:
/** * 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) { stack<TreeNode*> stack1; vector <int> result; bool visited; TreeNode *p = root,*q; if(!root) return result; do{ while(p!=NULL){ stack1.push(p); p = p->left; } visited = true; q = NULL; while(!stack1.empty() && visited){ p = stack1.top(); if(p ->right ==q){ result.push_back(p->val); stack1.pop(); q = p; } else{ p = p->right; visited =false; } } }while(!stack1.empty()); return result; }};
0 0
- LeetCode:Binary Tree Postorder
- leetcode Binary Tree Postorder
- 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
- Chrome插件开发学习心得(四)之修改浏览器菜单
- java 串行化学习
- poj 2719 丑陋的模拟/神奇的九进制(不能显示4的里程计)
- JAVA类中的equals()方法和hashCode()方法的重写
- 处理对象
- leetcode Binary Tree Postorder
- Ubuntu: 如何在开机的时候进入命令行
- OpenCV2学习笔记(四):两种图像分割方法比较
- 类成员
- poj2104 K-th Number(划分树)
- Printf Java
- swift语言IOS8开发战记22 Core Data3
- 采用深度学习算法为Spotify做基于内容的音乐推荐
- 最简单的音乐播放器,实现基本功能(二)