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?

Recursive Version

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if(root == null) return res;
        
        if(root.left != null){
            /*  ArrayList : addAll(int index, Collection<? extends E> c)
             *  Inserts all of the elements in the specified collection into this list, starting at the specified position.
             */
            res.addAll(inorderTraversal(root.left)); 
        }
        res.add(root.val);
        if(root.right != null){
            res.addAll(inorderTraversal(root.right)); 
        }
        
        return res;
    }
}

 Iterative Version

public class Solution {
   public  ArrayList<Integer> inorderTraversal(TreeNode root) {
            ArrayList<Integer> res = new ArrayList<Integer>();
            if(root==null) return res;
            
            Stack<TreeNode> s = new Stack<TreeNode>();
            TreeNode cur = root;
            while(!s.isEmpty()||cur!=null){
               if(cur!=null){
                    s.push(cur); 
                    cur=cur.left;
                }else{
                    cur=s.pop();
                    res.add(cur.val);
                    cur=cur.right;
                }
            }
            return res;
        }
}

DP

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

ref: http://www.cnblogs.com/feiling/p/3256607.html

原文地址:https://www.cnblogs.com/RazerLu/p/3536928.html