做剑指offer时都不需要自己初始化二叉树,但是有些时候必须自己初始化二叉树
所以就有了这次记录
代码如下:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct BTree{
struct BTree *left;
struct BTree *right;
int val;
}Tree;
//这里假设为完全二叉树故判断条件有一个index>v.size()
void creTree(struct BTree* head,vector<int>v,int index){
if(v.size()==0||head==NULL||index>v.size()||index<0)return;
int last=v.size()-1;
if(2*index+1<=last){
head->left=new struct BTree();
head->left->val=v[2*index+1];
}else{
head->left=NULL;
}
if(2*index+2<=last){
head->right=new struct BTree();
head->right->val=v[2*index+2];
}else{
head->right=NULL;
}
creTree(head->left,v,2*index+1);
creTree(head->right,v,2*index+2);
}
struct BTree * create(vector<int>v){
if(v.size()==0){
return NULL;
}
struct BTree* head=new struct BTree();
head->val=v[0];
creTree(head,v,0);
return head;
}
int main(){
int n;
scanf("%d",&n);
vector<int>v(n);
for(int i=0;i<n;++i){
scanf("%d",&v[i]);
}
struct BTree* head=new struct BTree();
head=create(v);
//以下为层次遍历二叉树,查看是否正确
queue<struct BTree*>q;
if(head!=NULL){
q.push(head);
}
while(!q.empty()){
cout<<q.front()->val<<" ";
if(q.front()->left){
q.push(q.front()->left);
}
if(q.front()->right){
q.push(q.front()->right);
}
q.pop();
}
return 0;
}