Saturday, June 14, 2014

LeetCode: Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

Solution

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>();
        List<Integer> solution = new ArrayList<Integer>();
        TreeNode node = root;
        while(!stack.isEmpty() || node !=null)
        {
            if (node != null)
            {
                stack.push(node);
                node = node.left;
            }
            else
            {
                node = stack.pop();
                solution.add(node.val);
                node = node.right;
            }
        }
        return solution;
    }
}

Other solution:

This solution needs more space but is easier to understand.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayDeque<TreeNode> stack = new ArrayDeque<TreeNode>();
        List<Integer> solution = new ArrayList<Integer>();
        HashSet<TreeNode> used = new HashSet<TreeNode>();
        if(root!=null)
            stack.push(root);
        while(!stack.isEmpty())
        {
            TreeNode temp = stack.pop();
            if(used.contains(temp))
            {
                solution.add(temp.val);
                continue;
            }
            used.add(temp);
            if (temp.right != null)
                stack.push(temp.right);
            stack.push(temp);
            if (temp.left != null)
                stack.push(temp.left);
        }
        return solution;
    }
}

No comments :

Post a Comment