LeetCode-Binary Tree Postorder Traversal
来源:互联网 发布:c语言平方怎么写 编辑:程序博客网 时间:2024/06/05 11:33
题目不用多说,就是二叉树的后序遍历。如果是递归进行遍历,相信大家是都会的。这里说下用栈进行遍历的大体思路及代码:
思路
与前序遍历不同,如果用栈实现后序遍历,当遍历完某个子树后,需要判断之前遍历的是左子树还是右子树。如果是左子树,则要再遍历右子树。如果刚遍历的是右子树,则要访问根节点,并出栈。
代码
public class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); if(root == null){ return result; } Deque<TreeNode> stack = new ArrayDeque<TreeNode>(); TreeNode prev = null; while(true){ while(root != null){ stack.push(root); root = root.left; } if(!stack.isEmpty()){ TreeNode top = stack.peek(); if(top.right == null || (prev != null && prev == top.right)){ prev = stack.pop(); result.add(prev.val); }else{ root = top.right; } }else{ break; } } 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
- CentOS6.5系统下RPM包安装MySQL5.6
- iOS 集成银联支付(绕过文档的坑,快速集成)
- Source Insight函数调用关系显示设置http://blog.csdn.net/duanbeibei/article/details/24395777
- 关于网络图片的采样与压缩保存
- POJ 3259 Wormholes
- LeetCode-Binary Tree Postorder Traversal
- 中小型企业如何选择服务器配置?
- C语言主要做哪些方面的开发---一个来自“IT技术学习”微信群的问题及答复
- 玩转Android---UI篇---TextView(文本框)
- 喜闻乐见的 2048 游戏 (附源码)
- WebSocket对象的“readyState”属性记录连接过程中的状态值
- 在Ubuntu平台上创建Cordova Camera HTML5应用
- ABAP table control
- 均方根值(RMS)+ 均方根误差(RMSE)+标准差(Standard Deviation)