qq_41235711
2018-10-19 01:01
采纳率: 66.7%
浏览 1.1k

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

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

 #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条回答 默认 最新

  • threenewbee 2018-10-20 01:57

    给你修改好了,如果问题解决,麻烦点下我回答右边的采纳,并且同时采纳下 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;
    } 
    
    
    

    图片说明

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题