Description: 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?
1. Recursive implementation:
Update 13/01/2014:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void preorderTraversal(TreeNode root, ArrayList<Integer> preorder) {
if(root==null) return;
preorder.add(root.val);
preorderTraversal(root.left, preorder);
preorderTraversal(root.right, preorder);
return;
}
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> preorder = new ArrayList<Integer>();
preorderTraversal(root, preorder);
return preorder;
}
}
old version:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> preorder = new ArrayList<Integer>();
if(root==null) return preorder;
preorder.add(root.val);
if(root.left!=null) preorder.addAll(preorderTraversal(root.left));
if(root.right!=null) preorder.addAll(preorderTraversal(root.right));
return preorder;
}
}
2. Iterative implementation
1) Create an empty stack nodeStack and push root node to stack.
2) Do following while nodeStack is not empty.
….a) Pop an item from stack and print it.
….b) Push right child of popped item to stack
….c) Push left child of popped item to stack
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
ArrayList<Integer> preorder = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = null;
// empty tree
if(root==null) return preorder;
stack.push(root);
while(!stack.empty()) {
current = stack.pop();
preorder.add(current.val);
if(current.right!=null) stack.push(current.right); // push right subtree into stack
if(current.left!=null) stack.push(current.left); // push left subtree into stack
}
return preorder;
}
}