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 29 30
| class Solution { public List<Integer> postorderTraversal(TreeNode root) { if (root == null) return new ArrayList<>(); ArrayList<Integer> res = new ArrayList<>(); Deque<TreeNode> stack = new LinkedList<>(); TreeNode cur = root; TreeNode prev = null;
while (!stack.isEmpty() || cur != null) { while (cur != null) { stack.addLast(cur); cur = cur.left; } cur = stack.removeLast(); if (cur.right == null || cur.right == prev) { res.add(cur.val); prev = cur; cur = null; } else { stack.addLast(cur); cur = cur.right; } }
return res; } }
|