1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) return res; Deque<TreeNode> stack = new ArrayDeque<>(); Deque<Integer> q = new ArrayDeque<>(); stack.push(root); while(!stack.isEmpty()){ root = stack.pop(); q.push(root.val); if(root.left!=null){ stack.push(root.left); } if(root.right!=null){ stack.push(root.right); } } while(q.size()>0){ res.add(q.pop()); } return res; }
|