地址:https://leetcode.com/problems/binary-tree-level-order-traversal/
题目:
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]
,
return its level order traversal as:
理解:
二叉树的层序遍历。
实现:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
vector<int> tmp;
int cnt = q.size();
while (cnt) {
--cnt;
TreeNode* p = q.front();
q.pop();
tmp.push_back(p->val);
if (p->left)
q.push(p->left);
if (p->right)
q.push(p->right);
}
res.push_back(std::move(tmp));
}
return res;
}
};