102 Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

1. Question

Given a binary tree, return thelevel ordertraversal of its nodes' values. (ie, from left to right, level by level).

For example: Given binary tree[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

2. Implementation

(1) BFS

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();

        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        List<Integer> level = new ArrayList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            level = new ArrayList<>();

            for (int i = 0; i < size; i++) {
                TreeNode curNode = queue.remove();
                level.add(curNode.val);

                if (curNode.left != null) {
                    queue.add(curNode.left);
                }

                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
            res.add(level);
        }
        return res;
    }
}

(2) DFS

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();

        getLevelOrderByDFS(root, 0, res);
        return res;
    }

    public void getLevelOrderByDFS(TreeNode node, int depth, List<List<Integer>> res) {
        if (node == null) {
            return;
        }

        if (res.size() == depth) {
            res.add(new ArrayList<>());
        }

        res.get(depth).add(node.val);

        getLevelOrderByDFS(node.left, depth + 1, res);
        getLevelOrderByDFS(node.right, depth + 1, res);
    }
}

3. Time & Space Complexity

BFS: 时间复杂度:O(n) 空间复杂度:O(w)

DFS: 时间复杂度:O(n) 空间复杂度:O(h)

Last updated