classTreeNode { int val; TreeNode left; TreeNode right;
publicTreeNode(int val) { this.val = val; } }
publicclassPreorderTraversal { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = newArrayList<>();
if (root != null) { Stack<TreeNode> stack = newStack<>(); stack.push(root);
TreeNode tmp; while (!stack.isEmpty()) { tmp = stack.pop(); result.add(tmp.val);
if (tmp.right != null) { stack.push(tmp.right); }
if (tmp.left != null) { stack.push(tmp.left); } } }
return result; } }
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classPreorderTraversal: defpreorder_traversal(self, root): result = [] if root: stack = [] stack.append(root) while stack: tmp = stack.pop() result.append(tmp.val) if tmp.right: stack.append(tmp.right) if tmp.left: stack.append(tmp.left) return result
classPostorderTraversal: defpostorder_traversal(self, root): result = [] if root: stack = [] help_stack = [] stack.append(root) while stack: tmp = stack.pop() help_stack.append(tmp.val) if tmp.left: stack.append(tmp.left) if tmp.right: stack.append(tmp.right) while help_stack: result.append(help_stack.pop()) return result