102. Binary Tree Level Order Traversal

Given a binary tree, return thelevel ordertraversal 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]
]
``````

Thoughts:

1. PreOrder Traversal + Add a "depth" variable to keep track of what level curNode should be inserted into
2. Solve using Queue

Code 1

``````/**
* 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) {
levelOrderHelper(root,0);
}

void levelOrderHelper(TreeNode* cur, int depth){
if(!cur) return;

levelOrderHelper(cur-> left, depth + 1);
levelOrderHelper(cur-> right, depth + 1);
}
};
``````

Code 2

``````/**
* 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) {
queue <TreeNode*> q;
if(root) q.push(root);
while(!q.empty()){
int len = q.size();
vector<int> level;
for(int i = 0; i < len; i ++){
TreeNode* cur = q.front();
level.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
q.pop();
}
}
}
};
``````

Code 2: checking null at the current node

``````/**
* 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) {
queue <TreeNode*> q;
q.push(root);
while(!q.empty()){
int len = q.size();
vector<int> level;
for(int i = 0; i < len; i ++){
TreeNode* cur = q.front(); q.pop();
if (!cur) continue;
level.push_back(cur->val);
q.push(cur->left);
q.push(cur->right);
}