首页 > 代码库 > Binary Tree Inorder Traversal

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?

方法

二叉树的非递归中序遍历。

    public List<Integer> inorderTraversal(TreeNode root) {
    	List<Integer> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;
        while(node != null || !stack.isEmpty()) {
        	while(node != null) {
        		stack.push(node);
        		node = node.left;
        	}
        	TreeNode curNode = stack.pop();
        	list.add(curNode.val);
        	node = curNode.right;
        }
        return list;
    }


Binary Tree Inorder Traversal