【LeetCode】145. Binary Tree Postorder Traversal
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实现