102. Binary Tree Level Order Traversal

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

Problem

Given a binary tree, return the level order traversal 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]
]

Solution

/**
 * 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) {
        vector<vector<int>> nodes;
        if (root == nullptr) return nodes;
        vector<TreeNode*> current{root}, next;
        auto *curptr = &current;
        auto *nextptr = &next;
        while (!curptr->empty()) {
            nodes.push_back(vector<int>());
            nodes.back().reserve(curptr->size());
            nextptr->clear();
            nextptr->reserve(curptr->size() * 2);
            for (const auto *node: *curptr) {
                if (node->left) nextptr->push_back(node->left);
                if (node->right) nextptr->push_back(node->right);
                nodes.back().push_back(node->val);
            }
            auto *temp = curptr;
            curptr = nextptr;
            nextptr = temp;
        }
        return nodes;
    }
};
  • #tree

Last updated

Was this helpful?