Problem Description
Given a binary tree, return the preorder traversal of its nodes’ values.
Example
Given binary tree {1,#,2,3}:
1 2 3 4 5 6 7 |
1 \ 2 / 3 |
return [1,2,3].
Challenge
Can you do it without recursion?
Solution 1:
Non recursion
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 |
/** * @param root: The root of binary tree. * @return: Preorder in ArrayList which contains node values. */ public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> lst = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root != null) stack.push(root); while(!stack.isEmpty()) { TreeNode node = stack.pop(); lst.add(node.val); if(node.right != null) { stack.push(node.right); } if(node.left != null) { stack.push(node.left); } } return lst; } |
Solution 2 (recursion – divide & conquer)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * @param root: The root of binary tree. * @return: Preorder in ArrayList which contains node values. */ public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> lst = new ArrayList<Integer>(); if(root != null) { lst.add(root.val); lst.addAll(preorderTraversal(root.left)); lst.addAll(preorderTraversal(root.right)); } return lst; } |
Divide:
ArrayList lstLeft = preorderTraversal(root.left)
ArrayList lstRight = preorderTraversal(root.right)
Conquer:
lst.add(root.val);
lst.add(lstLeft);
lst.add(lstRight);