Binary Tree Level Order Traversal

Problem

Given a binary tree root, return the level order traversal of it as a nested list, where each sublist contains the values of nodes at a particular level in the tree, from left to right.

Examples

Example 1:

Input: root = [1,2,3,4,5,6,7]

Output: [[1],[2,3],[4,5,6,7]]

Example 2:

Input: root = [1]

Output: [[1]]

Example 3:

Input: root = []

Output: []

Constraints

  • 0 <= The number of nodes in the tree <= 1000.
  • -1000 <= Node.val <= 1000

You should aim for a solution with O(n) time and O(n) space, where n is the number of nodes in the given tree.

Solution

Use a vector to track current level. If node has left/right subtree, add that node to the current level list.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
 
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (!root) {return {}; }
        std::vector<std::vector<int>> lists;
        std::vector<TreeNode*> open = {root};
        std::vector<int> curr_level;
        std::vector<TreeNode*> next_level;
        while (!open.empty()) {
            curr_level.clear();
            next_level.clear();
            for (auto &&node : open) {
                curr_level.push_back(node->val);
                if (node->left) {
                    next_level.push_back(node->left);
                }
                if (node->right) {
                    next_level.push_back(node->right);
                }
            }
            open = std::move(next_level);
            lists.push_back(std::move(curr_level));
        }
        return lists;
    }
};