Given a binary tree, return the level order traversal of its nodes' values. (i.e, 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] ]
二叉树的层序遍历且要分行,此题是剑指offer面试题32的题目二。两个难点:1.如何实现层序遍历(广度优先遍历)2.如何分行
1.不管是优先遍历一副有向图还是一棵树,都要用到队列。
2.分行是一个难点,但理解起来很简单。变量tobeprinted表示在当前层中还没有打印的节点数,而变量nextLevel表示下一层的节点数。nextlevel在每次子节点入队的同时自增,这样就可以记录下下一层有多少个点。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (root == NULL)
return result;
vector<int> cur;
TreeNode* ptr;
int nextlevel = 0; int tobeprinted = 1;
Seq.push(root);
while (!Seq.empty())
{
ptr = Seq.front();
cur.push_back(ptr->val);
Seq.pop();
if (ptr->left != NULL)
{
++nextlevel;
Seq.push(ptr->left);
}
if(ptr->right != NULL)
{
++nextlevel;
Seq.push(ptr->right);
}
--tobeprinted;
if (tobeprinted == 0)
{
tobeprinted = nextlevel;
nextlevel = 0;
result.push_back(cur);
cur.erase(cur.begin(), cur.end());
}
}
return result;
}
vector<vector<int>> result;
queue<TreeNode*> Seq;
};