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]
]
解題思路:
本題讓我們求解數(shù)的寬度優(yōu)先遍歷,具體思路有使用隊列將每一層的節(jié)點保存下來,然后按照FIFO的選擇逐個遍歷,然后將每個節(jié)點的子節(jié)點存入隊列睦授,以此類推蔗崎。
具體代碼如下:
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;
}
};