题目:
这题本质上和上题从上到下打印二叉树Ⅰ是一样的,只不过涉及到如何分层。
这里我参考的是评论区K神的方法(我太笨了,第一时间没想到),每一次都动态获取当前队列的长度分层即可。
C++代码:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x),left(nullptr),right(nullptr){}
};
TreeNode* createTree(vector<int> a,int i){
if(a[i] == -1){
return nullptr;
}
TreeNode* root = new TreeNode(a[i]);
int leftson = i*2+1;
int rightson = i*2+2;
if(leftson<a.size()){
root->left = createTree(a,leftson);
}else{
root->left = nullptr;
}
if(rightson<a.size()){
root->right = createTree(a,rightson);
}else{
root->right = nullptr;
}
return root;
}
void inorder(TreeNode* root){
if(root==nullptr){
return;
}
inorder(root->left);
cout<<root->val<<" ";
inorder(root->right);
}
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode* > sup;
vector<vector<int> > ans;
if(root==nullptr){
return ans;
}
sup.push(root);
while(!sup.empty()){
vector<int> temp;
for(int i=sup.size();i>0;i--){//分层的关键sup.size()
TreeNode* node = sup.front();
temp.push_back(node->val);
sup.pop();
if(node->left!=nullptr){
sup.push(node->left);
}
if(node->right!=nullptr){
sup.push(node->right);
}
}
ans.push_back(temp);
}
return ans;
}
};
int main(){
vector<int> a = {3,9,20,-1,-1,15,7};
TreeNode* root = createTree(a,0);
inorder(root);
cout<<endl;
Solution solution;
vector<vector<int> > ans = solution.levelOrder(root);
for(int i=0;i<ans.size();i++){
for(int j=0;j<ans[i].size();j++){
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
}