[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?

https://oj.leetcode.com/problems/binary-tree-inorder-traversal/

 

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if(root==null)
            return res;
        inorder(res,root);
        return res;
    }
    private void inorder(List<Integer> res,TreeNode root){
        if(root!=null){
            inorder(res,root.left);
            res.add(root.val);
            inorder(res,root.right);
        }
    }
    
}
View Code

 

非递归法:左子树全部压栈,然后依次弹出,处理当前节点和右子树。stack为空跳出。

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null)
            return res;

        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode cur = root;

        while (true) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            if (stack.isEmpty())
                break;
            cur = stack.pop();
            res.add(cur.val);
            cur = cur.right;

        }

        return res;

    }    
    
}

 

 

参考:

http://blog.csdn.net/fightforyourdream/article/details/16857347

 

posted @ 2014-07-02 00:28  jdflyfly  阅读(131)  评论(0编辑  收藏  举报