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]
]
解题思路:
本题让我们求解数的宽度优先遍历,具体思路有使用队列将每一层的节点保存下来,然后按照FIFO的选择逐个遍历,然后将每个节点的子节点存入队列,以此类推。
具体代码如下:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ret;
queue<TreeNode*> level;
if(!root) return ret;
level.push(root);
while(!level.empty())
{
vector<int> curLevel;
int size = level.size();
for(int i = 0; i < size; ++i)
{
TreeNode* curr = level.front();
curLevel.push_back(curr->val);
level.pop();
if(curr->left) level.push(curr->left);
if(curr->right) level.push(curr->right);
}
ret.push_back(curLevel);
}
return ret;
}
};
网友评论