Given a binary tree, return the level order traversal 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 7return its level order traversal as:[ [3], [9,20], [15,7]]
bfs层序遍历整颗树。
/** * 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> levelOrder(TreeNode* root) { queue q; vector > ans; if (root == nullptr) return ans; q.push(root); while (!q.empty()) { vector v; int n = q.size(); while (n-- > 0) { TreeNode* u = q.front(); q.pop(); //cout << u->val << endl; v.push_back(u->val); if (u->left != nullptr) q.push(u->left); if (u->right != nullptr) q.push(u->right); } ans.push_back(v); } return ans; }};