0102. Binary Tree Level Order Traversal

https://leetcode.com/problems/binary-tree-level-order-traversal

Description

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Example 1:

**Input:** root = [3,9,20,null,null,15,7]
**Output:** [[3],[9,20],[15,7]]

Example 2:

**Input:** root = [1]
**Output:** [[1]]

Example 3:

**Input:** root = []
**Output:** []

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].

  • -1000 <= Node.val <= 1000

ac1: DFS, preorder traversal

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        helper(root, res, 0);
        return res;
    }

    private void helper(TreeNode root, List<List<Integer>> res, int level) {
        if (root == null) return;

        if (res.size() <= level) res.add(new ArrayList<Integer>());

        res.get(level).add(root.val);

        helper(root.left, res, level + 1);
        helper(root.right, res, level + 1);
    }
}

ac2: BFS, queue

  • LinkedList instantiate queue: Queue<TreeNode> q = new LinkedList<TreeNode>();

  • int levelNum = q.size(); this technique is pretty smart.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Queue<TreeNode> q = new LinkedList<TreeNode>();

        if (root == null) return res;

        q.offer(root);
        while (!q.isEmpty()) {
            int levelNum = q.size();
            List<Integer> tmpList = new ArrayList<Integer>();
            for (int i = 0; i < levelNum; i++) {
                TreeNode curr = q.poll();
                tmpList.add(curr.val);
                if (curr.left != null) q.offer(curr.left);
                if (curr.right != null) q.offer(curr.right);
            }
            res.add(tmpList);
        }

        return res;
    }
}

Last updated