More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/binary-tree-postorder-traversal/java
Given a binary tree, return the postordertraversal of its nodes' values.node
Example:post
Input: 1 \ 2 / 3 Output: [1,null,2,3][3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?ui
Method 1. Using one stack to store nodes, and another to store a flag wheather the node has traverse right subtree.spa
Method 2. Stack + Collections.reverse( list )code
Method 1htm
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 2blog
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; }
Complexityip
Time complexity : O(n)
Space complexity : O(nlogn)
1. linkedList.addFirst( e )
2. Collections.reverse( arraylist )
More:【目錄】LeetCode Java實現