Tags

/*
===>requirements:
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?

===>my comments:
write recursive method first before analysis:
        if(!root)
            return
        it(root->left)
        printout(root)
        it(root->right)

*/

/**
 * 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) {       
        List<Integer> l = new ArrayList<Integer>();
        if(root == null)
            return l;
        Stack<TreeNode> s = new Stack<TreeNode>();
        TreeNode cur = root;
        while(!s.empty() || cur!=null)
        {
            if(cur != null)
            {
                s.push(cur);
                cur = cur.left;
            }
            else
            {
                cur = s.pop();
                l.add(cur.val);
                cur = cur.right;
            }
        }
        return l;
    }
}
Advertisements