用数组递归建立二叉树出错?

递归建立的时候总是出现返回到上一层然后在上一层与下一层之间死循环?

 #include <iostream>
using namespace std;
#include <stdlib.h>
#define NULLVALUE 0

typedef int Elemtype;

typedef struct Tree{
    Elemtype data;
    struct Tree *LTree;
    struct Tree *RTree;
};

void Create(Tree *tree,Elemtype *data,int start,int len){
    if(data[start]==NULLVALUE||start>=len){
        cout<<222<<endl;//测试 
        return ;
    }
    else{cout<<data[start]<<endl;
        tree=(Tree *)malloc(sizeof(Tree));
        tree->data=data[start];
        Create(tree->LTree,data,++start,len);
        Create(tree->RTree,data,++start,len);
    }
}

void Print(Tree *tree){
    if(tree==NULL)
        return ;
    cout<<tree->data<<"  ";
    Print(tree->LTree);
    Print(tree->RTree);
}

int main(){
    Elemtype data[]={1,2,4,0,0,5,0,0,3,6,0,0,7};
    int len=sizeof(data)/sizeof(data[0]);
    Tree *tree;
    Create(tree,data,0,len);
    Print(tree);
    return 0;
}          

1个回答

给你修改好了,如果问题解决,麻烦点下我回答右边的采纳,并且同时采纳下 https://ask.csdn.net/questions/703225

// Q703225.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"


#include <iostream>
using namespace std;
#include <stdlib.h>
#define NULLVALUE 0

typedef int Elemtype;

typedef struct Tree{
    Elemtype data;
    struct Tree *LTree;
    struct Tree *RTree;
};

void Create(Tree **tree,Elemtype *data,int &start,int len){
    if(start>=len||data[start]==NULLVALUE){
        *tree = NULL;
        return ;
    }
    else{
        *tree=(Tree *)malloc(sizeof(Tree));
        (*tree)->data=data[start];
        ++start;
        Create(&(*tree)->LTree,data,start,len);
        ++start;
        Create(&(*tree)->RTree,data,start,len);
    }
}

void Print(Tree *tree){
    if(tree==NULL)
        return ;
    cout<<tree->data<<"  ";
    Print(tree->LTree);
    Print(tree->RTree);
}

int main(){
    Elemtype data[]={1,2,4,0,0,5,0,0,3,6,0,0,7};
    int len=sizeof(data)/sizeof(data[0]);
    Tree *tree=NULL;
    int start=0;
    Create(&tree,data,start,len);
    Print(tree);
    return 0;
} 


图片说明

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!