题目来源:
leetcode题目,网址:102. 二叉树的层序遍历 - 力扣(LeetCode)
解题思路:
从根节点开始,逐个取出该层的节点并将该节点的左右非空子节点加入队列中。
解题代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
queue<TreeNode*> myQueue;
if(root==nullptr){
return res;
}
myQueue.push(root);
while(myQueue.size()!=0){
vector<int> thisLevel;
int size=myQueue.size();
for(int i=0;i<size;i++){
TreeNode* temp=myQueue.front();
myQueue.pop();
thisLevel.push_back(temp->val);
if(temp->left!=nullptr){
myQueue.push(temp->left);
}
if(temp->right!=nullptr){
myQueue.push(temp->right);
}
}
res.push_back(thisLevel);
}
return res;
}
};
总结:
官方题解也是广度有限搜索。