Wednesday, July 1, 2015

Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.
Have you met this question in a real interview? 
Yes
Example
Given binary tree {1,#,2,3}:
1
 \
  2
 /
3
return [1,2,3].

Challenge
Can you do it without recursion?
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if(root != null)
        stack.push(root);
        while(!stack.isEmpty()){
            root = stack.pop();
            result.add(root.val);
            if(root.right != null) stack.push(root.right);
            if(root.left != null) stack.push(root.left);
        }
        return result;
    }
}

recursion:
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Preorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        recursion(root, result);
        return result;
    }
    private void recursion(TreeNode root,  ArrayList<Integer> result){
        if(root == null) return;
        result.add(root.val);
        recursion(root.left, result);
        recursion(root.right, result);
    }
}

No comments:

Post a Comment