题目:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
例如以下列出三种解法:一种迭代的和两种iterative的
import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Binary_Tree_Postorder_Traversal { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static void main(String[] args) { TreeNode r1 = new TreeNode(1); TreeNode r2 = new TreeNode(2); TreeNode r3 = new TreeNode(3); TreeNode r4 = new TreeNode(4); TreeNode r5 = new TreeNode(5); TreeNode r6 = new TreeNode(6); r1.left = r2; r1.right = r3; r2.left = r4; r2.right = r5; r3.right = r6; List pr = postorderTraversal1(r1); int size = pr.size(); System.out.println("the size is " + size); for (int i =0 ; i< size; i++) { System.out.println(pr.get(i)); } } public static List<Integer> postorderTraversal1(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); if (root == null) return result; result.addAll(postorderTraversal1(root.left)); result.addAll(postorderTraversal1(root.right)); result.add(root.val); return result; } public static List<Integer> postorderTraversal2(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); Stack<TreeNode> output = new Stack<TreeNode>(); if (root == null) return result; stack.push(root); while(!stack.empty()) { TreeNode cur = stack.pop(); output.push(cur); if(cur.left != null) { stack.push(cur.left); } if(cur.right != null) { stack.push(cur.right); } } while(!output.isEmpty()) { result.add(output.pop().val); } return result; } public List<Integer> postorderTraversal3(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode prev = null; // previously traversed node TreeNode curr = root; if (root == null) { return result; } stack.push(root); while (!stack.empty()) { curr = stack.peek(); if (prev == null || prev.left == curr || prev.right == curr) { // traverse down the tree if (curr.left != null) { stack.push(curr.left); } else if (curr.right != null) { stack.push(curr.right); } } else if (curr.left == prev) { // traverse up the tree from the left if (curr.right != null) { stack.push(curr.right); } } else { // traverse up the tree from the right result.add(curr.val); stack.pop(); } prev = curr; } return result; } }