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
| public static void iterativePreOrder(TreeNode p) { if (p == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); while (!stack.empty() || p != null) { while (p != null) { visit(p); stack.push(p); p = p.left; } p = stack.pop(); p = p.right; } }
public static void iterativePreOrder_2(TreeNode p) { if (p == null) return; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(p); while (!stack.empty()) { p = stack.pop(); visit(p); if (p.right != null) stack.push(p.right); if (p.left != null) stack.push(p.left); } }
|