102. Binary Tree Level Order Traversal

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 {
    vector<vector<int>> res;
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        levelOrder_bf(root, 0);
        
        return res;
    }
    
    void levelOrder_bf(TreeNode* node, int level) {
        if (node == nullptr) {
            return;
        }
        
        if (res.size() == level) {
            res.push_back(vector<int>());
        }
        
        res[level].push_back(node->val);
        levelOrder_bf(node->left, level + 1);
        levelOrder_bf(node->right, level + 1);
    }
};

Complexity

  • Time Complexity: O(N), where N is the number of noded.
  • Space Complexity: O(logN), where N is the number of nodes.

All Solutions