leetcode 63: Binary Tree Inorder Traversal

Binary Tree Inorder TraversalAug 27 '12

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? > read more on how binary tree is serialized on OJ.

 

 

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ArrayList<Integer> list = new ArrayList<Integer>();
    
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // Start typing your Java solution below
        // DO NOT write main() function
        list.clear();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode tn = root;
        
        while( !stack.empty() || tn !=null ) {
            if(tn != null) {
                stack.push(tn);
                tn = tn.left;
            } else {
                tn = stack.pop();
                list.add(tn.val);
                tn = tn.right;
            }
        }
        return list;
    }
}


 

posted @ 2013-01-29 13:28  西施豆腐渣  阅读(119)  评论(0编辑  收藏  举报