94. Binary Tree Inorder Traversal (Medium)

Given a binary tree, return theinordertraversal of its nodes' values.

For example:
Given binary tree[1,null,2,3],

   1
    \
     2
    /
   3

return[1,3,2].

Note:Recursive solution is trivial, could you do it iteratively?

Solution 1: Recursive, DFS O(n); O(h)
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        dfs(res, root);
        return res;
    }

    private void dfs(List<Integer> res, TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(res, root.left);
        res.add(root.val);
        dfs(res, root.right);
    }
Solution 2: Iterative + Stack O(n); O(h)
     1
    / \
   2   3
  / \  /\
 4   5 6 7
 stack: 1 2 4
 cur: 4 2 5 1 
 stack: 3 6
 cur: 6 3 7
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (!stack.empty() || cur != null) {
            while (cur != null) {
                stack.push(cur); //cur, not cur.left
                cur = cur.left;
            }
            cur = stack.pop();
            res.add(cur.val);
            cur = cur.right;
        }
        return res;
    }

results matching ""

    No results matching ""