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实现

最新文章

  1. Maven环境配置
  2. Daily Scrum02 12.13
  3. Ambari server:无法显示内存,CPU等使用率
  4. 查找SQL SERVER被锁的表和解决方法
  5. 持续集成(CI)相关的一些工具,后续补充。。。。
  6. MySQL各逻辑模块工作配合
  7. struts2 token 使用说明
  8. MVC中——Layout和ViewStart以及页面Index之间的关系
  9. iOS 三维变换
  10. ural 1100. Final Standings(数据结构)
  11. JAVA文件名命名规范
  12. 神经网络3_M-P模型
  13. 使用soupUI做接口测试
  14. python按行遍历一个大文件,最优的语法应该是什么?
  15. linux系统关闭指定服务的方式
  16. WannaCry勒索病毒全解读,权威修复指南大集合
  17. 洛谷luogu2782
  18. day21 MRO和C3算法
  19. Spring ApplicationContext(一)初始化过程
  20. SPFA_queue_链式前向星最短路 &amp; HDU2433

热门文章

  1. 好用的APS系统是什么样的?这篇文章来告诉你!
  2. ANDROID培训准备资料之Service
  3. SQL中的连接(极客时间)
  4. apache主配置文件设置
  5. Jenkins-Master-slave架构(八)
  6. Alpha2项目的测试
  7. Rust中的字符串处理
  8. c# 第七节 编程规范,vs中的各种设置
  9. 1.python进行if条件相等时候的条件
  10. Maven 拥有三套相互独立的生命周期:clean、default、site