C++| BFS | DFS | O(N) | Explained ✔
Intuition\n Describe your first thoughts on how to solve this problem. \nSo we have to go level by level and check for each node its left and right if they exit
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo we have to go level by level and check for each node its left and right if they exitst or one of them exist push that in queue. ALso queue will be initailly pushed with root node.\nThe idea behind using the queue is since we go from left ---> right \nso when taking the elemnts we want in same manner so queue is first in first out data structure it completely suits here (not stack which will give elemnts in reverse order).\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Breadth first search  or Level Order Traversal\n- DFS or PreOrder Traversal but using level varaible to push level wise .\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n**BFS**\n```\nclass Solution {\npublic:\n    vector<vector<int>> levelOrder(TreeNode* root) {\n    vector<vector<int>>ans;\n        if(!root)return ans;\n        queue<TreeNode*>q;\n        q.push(root);\n        while(!q.empty()){\n           int sz=q.size();\n           vector<int>v;\n           while(sz--){\n               TreeNode * f=q.front();\n               v.push_back(q.front()->val);\n               q.pop();\n               if(f->left)q.push(f->left);\n               if(f->right)q.push(f->right);\n\n           }\n           ans.push_back(v);\n        }\n        return ans;\n    }\n};\n```\n**DFS**\n```\nclass Solution {\npublic:\n    void dfs(TreeNode * root ,vector<vector<int>>&ans,int d=0){\n      if(!root)return;\n      if(d>=ans.size())ans.push_back({});\n      ans[d].push_back(root->val);\n      dfs(root->left,ans,d+1);\n      dfs(root->right,ans,d+1);\n  }\n    vector<vector<int>> levelOrder(TreeNode* root) {\n        vector<vector<int>>ans;\n        if(!root)return ans;\n         if(!root)return ans;\n         dfs(root,ans);\n        return ans;\n    }\n};\n```\n# Upvoye If Help FUll \uD83D\uDD3C\uD83D\uDD3C\uD83D\uDD3C
['Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'C++']