LeetCode 解题报告 Binary Tree Postorder Traversal
来源:互联网 发布:圈圈助手源码 编辑:程序博客网 时间:2024/05/17 22:32
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]
.
分析:
不用递归来求二叉树的后序遍历,那首先等想到的就是用栈来模拟。
首先从根节点开始,遍历左子树并进站。
直至左子树空,然后弹出最后一个进入栈的元素,并判断其右子树
如果右子树为空,或者访问过了,就将其加入到结果集中,
否则,现将弹出的结点再次进栈,然后指向其右结点
public List<Integer> postorderTraversal(TreeNode root) { Stack<TreeNode> stack = new Stack<TreeNode>(); List<Integer> result = new LinkedList<Integer>(); TreeNode node = root; do{ //将左子树入栈 while(node != null){ stack.push(node); node = node.left; } TreeNode temp = null; while(!stack.empty()){ node = stack.peek(); stack.pop(); //这个节点没有右孩子,或者被访问过了 if(node.right == temp){ result.add(node.val); temp = node; }else{ stack.push(node); node = node.right; break; } } }while(!stack.isEmpty()); 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 OJ] Binary Tree Postorder Traversal 解题报告
- LeetCode(145) Binary Tree Postorder Traversal解题报告
- [leetcode] 145. Binary Tree Postorder Traversal 解题报告
- 【LeetCode】145. Binary Tree Postorder Traversal 解题报告
- [Leetcode] 145. Binary Tree Postorder Traversal 解题报告
- [leetcode]145. Binary Tree Postorder Traversal@Java解题报告
- 【LeetCode】145.Binary Tree Postorder Traversal(Hard)解题报告
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode(106) Construct Binary Tree from Inorder and Postorder Traversal解题报告
- [leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode 解题报告 Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal 解题报告
- LeetCode 145:Binary Tree Postorder Traversal 解题与思考
- 算法导论-第14章-数据结构的扩张
- SQLServer事务复制在不重新初始化的情况下添加新表
- 模态对话框中,父调用子数据,子保存上次更改的数据
- 【bzoj 1816】: [Cqoi2010]扑克牌
- 重创股金
- LeetCode 解题报告 Binary Tree Postorder Traversal
- 怎样使用JPG转PDF转换器转换图片
- 协方差矩阵的详细说明
- 电子书全地址
- phpcms 采集使用讲解与注意事项
- 多选下拉框
- 爱你哟收吧 欧巴
- 短信api服务
- CentOS 6.5 64位安装JDK、tomcat