C++ | BFS and DFS Dual Approaches | Beats 100% ✅
Upvote if you like the post :)\n\nApproach 1/Recursive/DFS :\nLet\'s just keep a count of each level and visit every node in left to right order.\n\n\nclass Sol
`Upvote if you like the post :)`\n\n**Approach 1/Recursive/DFS :**\nLet\'s just keep a count of each level and visit every node in left to right order.\n\n```\nclass Solution {\npublic:\n    vector<vector<int>> ans;\n    \n    void dfs(TreeNode* root, int level){\n        if(!root)\n            return;\n        if(level==ans.size()){\n            ans.push_back({});\n        }\n        ans[level].push_back(root->val);\n        dfs(root->left,level+1);\n        dfs(root->right,level+1);\n    }\n    vector<vector<int>> levelOrder(TreeNode* root) {\n        \n        dfs(root,0);\n        return ans;\n    }\n};\n```\n****\n**Time Complexity : O(N)**\n**Space Complexity: O(H)**, `H `being the `height` of the tree\n****\n**Approach 2/Iterative/BFS:**\nThe `idea` remains the `same`, just that we will be using a `queue` instead.\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            vector<int> level;\n            int size = q.size();\n            for(int i=0;i<size;i++){\n                TreeNode* node = q.front();\n                q.pop();\n                if(node->left!=NULL) q.push(node->left);\n                if(node->right!=NULL)q.push(node->right);\n                level.push_back(node->val);\n            }\n            ans.push_back(level);\n        }\n        return ans;\n    }\n};\n```\n****\n**Time Complexity : O(N)**\n**Space Complexity: O(W)**, `W `being the `Width` of the tree\n****
['Breadth-First Search', 'Queue', 'C', 'C++']