层次遍历数组建立二叉树
约定:层次遍历数组中为空的结点记为0
解析
使用递归,检查每个结点的左右结点是否存在,存在即分配结点,并递归检查该结点。
void insert(TreeNode *p, vector<int> temp, int t){
int length = temp.size();
if(t>=length)return;
p->val = temp[t];
if((2 * (t+1)) <= length){
if(temp[2 * (t+1) -1]!=0){
TreeNode *l;
l = (TreeNode*)malloc(sizeof(TreeNode));
l->left = NULL;
l->right = NULL;
p->left = l;
insert(p->left, temp, 2 * (t+1) -1);
}
if((2 * (t+1) +1) <= length){
if(temp[2 * (t+1)]!=0){
TreeNode *r;
r = (TreeNode*)malloc(sizeof(TreeNode));
r->left = NULL;
r->right = NULL;
p->right = r;
insert(p->right, temp, 2 * (t+1));
}
}
}
}
TreeNode* createFromArray(vector<int> temp){
TreeNode *p;
p = (TreeNode*)malloc(sizeof(TreeNode));
p->left = NULL;
p->right = NULL;
insert(p,temp,0);
return p;
}