---
# System prepended metadata

title: 'Leetcode : 0102. Binary Tree Level Order Traversal (Tree)'
tags: [leetcode]

---

# Leetcode : 0102. Binary Tree Level Order Traversal (Tree)
###### tags:`leetcode`

```
/**
 * 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) {}
 * };
 */
 
> DFS Method

class Solution {
public:
    void leveltraversal(TreeNode* root , int level , vector<vector<int>> &ans){
        if(!root)return;
        /*
        if(ans.size()==level){
            ans.push_back({root->val}); //level not any val add it
        }else{
            ans[level].push_back(root->val); //add level last val(push_back)
        }
        */
        
        if (ans.size() <= level) {
            ans.push_back({});
        }
        ans[level].push_back(root -> val);
        
        leveltraversal(root->left, level+1 , ans);
        leveltraversal(root->right, level+1 , ans);
    }

    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        leveltraversal(root, 0 , ans);
        return ans;
    }
};
//T(n)-O(N) n- no.of nodes in the tree S(n)=O(H)(recursion stack)
```

```
/**
 * 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) {
        if (!root) {
            return {};
        }
        vector<vector<int>> levels;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            levels.push_back({});//new turn add level {}
            for (int i = 0, n = q.size(); i < n; i++) {
                TreeNode* node = q.front(); // save now 
                q.pop();
                levels.back().push_back(node -> val); // back last array and last add val
                if (node -> left) { // if have left push in queue
                    q.push(node -> left); 
                }
                if (node -> right) { // if have right push in queue
                    q.push(node -> right);
                }
            }
        }
        return levels;
    }
};
```