题目
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 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
分析
- 用队列保存未访问节点
- 一个变量保存当前层中未被访问的节点数目
- 另一个变量表示下一层的节点数目
实现
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> res;
if (root == NULL)
return res;
//remainNum 标记本层剩余的结点数目
//childNum 标记下一层的子节点数目
int remainNum = 1, childNum = 0;
vector<int> tmpRes;
//队列记录所有未被访问结点
queue<TreeNode*> que;
que.push(root);
TreeNode * currNode = NULL;
while (remainNum||childNum)
{
currNode = que.front();
tmpRes.push_back(currNode->val);
if (currNode->left)
{
childNum++;
que.push(currNode->left);
}
if (currNode->right)
{
childNum++;
que.push(currNode->right);
}
que.pop();
remainNum--;
if (remainNum == 0)
{
res.push_back(tmpRes);
tmpRes.clear();
remainNum = childNum;
childNum = 0;
}
}
return res;
}
};