Wednesday, March 4, 2015

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?
confused what "{1,#,2,3}" means?
Solution: iterator
用一个stack来模拟递归的过程。所以算法时间复杂度是O(n),空间复杂度是栈的大小O(logn)
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList inorderTraversal(TreeNode root) {
        ArrayList res = new ArrayList();
        LinkedList stack = new LinkedList();
        
        if(root == null)
            return res;

        while(!stack.isEmpty() || root != null) {
            if(root != null) {
                stack.push(root);
                root = root.left;
            }else {
                TreeNode temp = stack.pop();
                res.add(temp.val);
                root = temp.right;
            }
        }
        return res;
    }
}

No comments:

Post a Comment