Wednesday, July 1, 2015

Binary Tree Inorder Traversal

Binary Tree Inorder Traversal

39%
Accepted
Given a binary tree, return the inorder 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,3,2].
Challenge
Can you do it without recursion?

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> result = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
     
        while(!stack.isEmpty() || root != null){
            if(root != null){
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                result.add(root.val);
                root = root.right;
            }
        }
        return result;
    }
}
recursion:
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Inorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> inorderTraversal(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;
        recursion(root.left, result);
        result.add(root.val);
        recursion(root.right, result);
    }
}


No comments:

Post a Comment