102. Binary Tree Level Order Traversal
1. Description
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
2. Solutions
My Accepted Solution
n is the number of nodes in i_root
Time complexity: O(n)
Space complexity: O(n)
class Solution
{
public:
// vector<vector<int>> levelOrder(TreeNode* root)
vector<vector<int>> levelOrder(const TreeNode *i_root)
{
if(!i_root) return vector<vector<int>>{};
vector<vector<int>> result;
queue<const TreeNode *> currentLevelNodes{{i_root}};
queue<const TreeNode *> nextLevelNodes;
vector<int> levelNodesValue;
while(!currentLevelNodes.empty() || !nextLevelNodes.empty())
{
if(currentLevelNodes.empty())
{
result.push_back(levelNodesValue);
levelNodesValue.clear();
swap(currentLevelNodes, nextLevelNodes);
}
else
{
auto node = currentLevelNodes.front();
currentLevelNodes.pop();
levelNodesValue.push_back(node->val);
if(node->left) nextLevelNodes.push(node->left);
if(node->right) nextLevelNodes.push(node->right);
}
}
result.push_back(levelNodesValue);
return result;
}
};