Leetcode 102. Binary Tree Level Order Traversal
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).
root
is NULL
)?
queue
to keep track of nodes at each level.#include <vector>
#include <queue>
#include <iostream>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if (!root) {
return result; // Return an empty result if the tree is empty.
}
queue<TreeNode*> q; // Queue for storing nodes at each level.
q.push(root);
while (!q.empty()) {
int level_size = q.size(); // Number of nodes at the current level.
vector<int> current_level; // To store node values at the current level.
for (int i = 0; i < level_size; ++i) {
TreeNode* node = q.front();
q.pop();
current_level.push_back(node->val);
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
result.push_back(current_level); // Add the current level to the result.
}
return result;
}
};
n
is the number of nodes in the tree. This is because we visit each node exactly once.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?