LeetCode -- Binary Tree Inorder Traversal

Question:

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?

 

Analysis:

给出一棵二叉树,返回它节点值的中序遍历。

Note:递归的解决方案是简单的,你能用循环的方式解决吗?

 

思路1:递归的解决方案:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    List<Integer> result = new ArrayList<Integer>();
    public List<Integer> inorderTraversal(TreeNode root) {
        tra(root);
        return result;
    }
    public void tra(TreeNode root) {
        if(root == null) return;
        if(root.left != null) tra(root.left);
        result.add(root.val);
        if(root.right != null) tra(root.right);
    }
}

 

 

思路二:非递归遍历方式。使用一个栈,记录遍历过程中回退的路径。在一棵子树中首先访问的是中序下的第一个结点,它位于从根开始沿leftChild链走到最左下角的结点。访问它的数据之后,再遍历该结点的右子树。重复以上过程。

/**
 * Definition for a binary tree node.
 * 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> list = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = root;
        do {
            while(p != null) {
                stack.push(p);
                p = p.left;
            }
            if(!stack.isEmpty()) {
                p = stack.pop();
                list.add(p.val);
                p = p.right;
            }
        } while(p != null || !stack.isEmpty());
        return list;
    }
} 
posted @ 2016-03-02 09:30  江湖小妞  阅读(199)  评论(0编辑  收藏  举报