代码之家  ›  专栏  ›  技术社区  ›  Karthik

使用三重指针插入二叉树

  •  0
  • Karthik  · 技术社区  · 7 年前

    请查找上述主题的代码。我正在尝试使用三重指针创建/插入二叉树,但在 insert() insert(&(**tree)->lchild),data) .

    请告诉我如何绕过这个问题。

    struct node
    {
        int data;
        struct node* lchild;
        struct node *rchild;
        int count;
        int visited;
    };
    
    void sub_arry(int *arr1,int *arr2,struct node **tree);
    
    void insert(struct node ***tree,int data);
    
    int main()
    {
        int arr1[]={2,1,2,5,7,1,9,3,6,8,8};
        int arr2[]={2,1,8,3};
        struct node *tree =NULL;
        sub_arry(arr1,arr2,&tree);
        return 0;
    }
    
    void sub_arry(int *arr1,int *arr2,struct node **tree)
    {
        int i;
        int n = sizeof(arr1)/sizeof(arr1[0]);
        int m = sizeof(arr2)/sizeof(arr2[0]);
        for(i=0;i<n;i++)
        {
            insert(&tree,arr1[i]);
        }
    }
    
    void insert(struct node ***tree,int data)
    {
        struct node *root;
        if (**tree == NULL)
        {
            root = (struct node *)malloc(sizeof(struct node));
            root->data = data;
            root->lchild = NULL;
            root->rchild = NULL;
            root->count = 1;
            **tree = root;
            return;
        }
        if(data == (**tree)->data)
            (**tree)->count += 1;
        else if(data > (**tree)->data)
            insert(&((*(*tree))->rchild),data); //rchild is of struct node*
        else
            insert(&(**tree)->lchild,data);   //lchild is of struct node *
        return;
    }
    
    0 回复  |  直到 7 年前