【LeetCode】145. Binary Tree Postorder Traversal
2024-10-09 08:20:17
Difficulty: Hard
More:【目录】LeetCode Java实现
Description
https://leetcode.com/problems/binary-tree-postorder-traversal/
Given a binary tree, return the postordertraversal of its nodes' values.
Example:
Input:[1,null,2,3]
1
\
2
/
3 Output:[3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
Intuition
Method 1. Using one stack to store nodes, and another to store a flag wheather the node has traverse right subtree.
Method 2. Stack + Collections.reverse( list )
Solution
Method 1
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new LinkedList<Integer>();
Stack<TreeNode> nodeStk = new Stack<TreeNode>();
Stack<Boolean> tag = new Stack<Boolean>();
while(root!=null || !nodeStk.isEmpty()){
while(root!=null){
nodeStk.push(root);
tag.push(false);
root=root.left;
}
if(!tag.peek()){
tag.pop();
tag.push(true);
root=nodeStk.peek().right;
}else{
list.add(nodeStk.pop().val);
tag.pop();
}
}
return list;
}
Method 2
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> list = new LinkedList<Integer>();
Stack<TreeNode> stk = new Stack<>();
stk.push(root);
while(!stk.isEmpty()){
TreeNode node = stk.pop();
if(node==null)
continue;
list.addFirst(node.val); //LinkedList's method. If using ArrayList here,then using 'Collections.reverse(list)' in the end;
stk.push(node.left);
stk.push(node.right);
}
return list;
}
Complexity
Time complexity : O(n)
Space complexity : O(nlogn)
What I've learned
1. linkedList.addFirst( e )
2. Collections.reverse( arraylist )
More:【目录】LeetCode Java实现
最新文章
- Maven环境配置
- Daily Scrum02 12.13
- Ambari server:无法显示内存,CPU等使用率
- 查找SQL SERVER被锁的表和解决方法
- 持续集成(CI)相关的一些工具,后续补充。。。。
- MySQL各逻辑模块工作配合
- struts2 token 使用说明
- MVC中——Layout和ViewStart以及页面Index之间的关系
- iOS 三维变换
- ural 1100. Final Standings(数据结构)
- JAVA文件名命名规范
- 神经网络3_M-P模型
- 使用soupUI做接口测试
- python按行遍历一个大文件,最优的语法应该是什么?
- linux系统关闭指定服务的方式
- WannaCry勒索病毒全解读,权威修复指南大集合
- 洛谷luogu2782
- day21 MRO和C3算法
- Spring ApplicationContext(一)初始化过程
- SPFA_queue_链式前向星最短路 &; HDU2433