102. 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],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
題意:二叉樹的層序遍歷
思路:BFS壳嚎,應(yīng)該很熟練了
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;//建立一個(gè)樹的隊(duì)列
vector<vector<int>> res;
if (root == NULL)
return res;
q.push(root);
while(!q.empty())
{
int size=q.size();
vector<int>v;
while(size--)
{
TreeNode* node=q.front();
q.pop();
v.push_back(node->val);
if(node->left!=NULL)
q.push(node->left);
if(node->right!=NULL)
q.push(node->right);
}
res.push_back(v);
}
return res;
}
};