Problem

Given a binary tree, return the inorder traversal of its nodes' values.

Example

Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3
 

return [1,3,2].

Challenge

Can you do it without recursion?

Note

递归法不说了,栈迭代的helper函数是利用stackLIFO原理,从根节点到最底层的左子树,依次push入堆栈。然后将pop出的结点值存入数组,并对pop出的结点的右子树用helper函数继续迭代。

Solution

Recursion

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

Stack Iteration

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

Another Stack Iteration

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

linspiration
161 声望53 粉丝