Link: http://oj.leetcode.com/problems/binary-tree-preorder-traversal/
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
Recursion version:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 ArrayList<Integer> nodes = new ArrayList<Integer>(); 12 13 public ArrayList<Integer> preorderTraversal(TreeNode root) { 14 15 preorderTraversal_recursion(root); 16 return nodes; 17 } 18 public void preorderTraversal_recursion(TreeNode root){ 19 if(root==null) 20 return; 21 nodes.add(root.val); 22 preorderTraversal_recursion(root.left); 23 preorderTraversal_recursion(root.right); 24 25 } 26 }
Iteration version:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public ArrayList<Integer> preorderTraversal(TreeNode root) { 12 ArrayList<Integer> nodes = new ArrayList<Integer>(); 13 if (root == null) 14 return nodes; 15 Stack<TreeNode> stack = new Stack<TreeNode>(); 16 // this is used to identify the node pop from stack 17 TreeNode node; 18 stack.push(root); 19 while (!stack.isEmpty()) { 20 node = stack.pop(); 21 nodes.add(node.val); 22 if (node.right != null) 23 stack.push(node.right); 24 if (node.left != null) 25 stack.push(node.left); 26 } 27 return nodes; 28 } 29 }