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,应该很熟练了
/**
* 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;//建立一个树的队列
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;
}
};
网友评论