Wednesday, August 13, 2014

Leetcode: 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?


Understand the problem:
The problem asks for a preorder traversal of a binary tree. So first of all, you should understand what is preorder traversal of a binary tree. There is a post described about the tree traversal in detail. 
http://www.cs.cmu.edu/~adamchik/15-121/lectures/Trees/trees.html

Basically, preorder traversal is to visit the parent first, then left children, then right children. 

Recursive Approach:
The recursive approach is very straight-forward, just as how the binary tree is defined. 

Code (Java):
/**
 * 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> result = new ArrayList<Integer>();
        
        preorderTraversal(root, result);
        return result;
    }
    
    private void preorderTraversal(TreeNode node, ArrayList<Integer> result) {
        if (node == null) return;
        
        result.add(node.val);
        if (node.left != null) preorderTraversal(node.left, result);
        if (node.right != null) preorderTraversal(node.right, result);
    }
}

Discussion:
The method takes O(n) time since we traverse all nodes of the tree. The space complexity is O(h) where h is the height of the tree.

Iterative approach:
In the iterative approach, we use a stack to store the intermediate data, just to mimic the recursive approach. The algorithm pops a node from the stack and prints the current value and push its right child into the stack, then push its left child into the stack. 

Code (Java):
/**
 * 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> result = new ArrayList<Integer>();
        if (root == null) return result;
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        stack.push(root);
        while (! stack.isEmpty()) {
            TreeNode temp = stack.pop();
            result.add(temp.val);
            
            if (temp.right != null) stack.push(temp.right);
            if (temp.left != null) stack.push(temp.left);
        }
        return result; 
    }
}


Summary:
In this post, we learned the preorder binary tree traversal. The recursive approach is straight-forward to implement. But make sure you understand the details. The iterative approach is close to recursive, but using a stack explicitly. In many tree-based problem, a stack is commonly used in iterative approach. 

Update on 9/29/14:


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        if (root == null) {
            return result;
        }
        
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        
        while (!stack.isEmpty()) {
            TreeNode curr = stack.pop();
            result.add(curr.val);
            
            if (curr.right != null) {
                stack.push(curr.right);
            }
            
            if (curr.left != null) {
                stack.push(curr.left);
            }
        }
        
        return result;
    }
}



Update on 9/30/14:
Divide-and-Conquer:
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;<pre class="brush:java">
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        
        if (root == null) {
            return result;
        }
        
        // Divide 
        List<Integer> left = preorderTraversal(root.left);
        List<Integer> right = preorderTraversal(root.right);
        
        result.add(root.val);
        result.addAll(left);
        result.addAll(right);
        
        return result;
    }
}

No comments:

Post a Comment