Given the root
of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).
Example:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] Input: root = [1] Output: [[1]] Algorithm: Since we have to traverse the tree level wise and need to process node from left to right, we can use Queue here and push nodes at each level, traverse it and process it further. vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ans; 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 *node = q.front(); level.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); q.pop(); } ans.push_back(level); } return ans; }