使用指针问题的二进制搜索树

问题描述 投票:0回答:1

im对使用c ++进行编码来说相对较新,我试图在c ++和im中使用指针来实现此目的,但是即使经过几个小时,我也无法弄清指针中的错误,基本上该错误出现在if语句中,im试图使用递归当父级根目录中有子级时更改根目录,这里是代码

#include<iostream>
using namespace std;

struct node{
    struct node* rightchild;
    int data;
    struct node* leftchild;
};

struct node* newNode(int data){
    struct node* node1 = (node*)malloc(sizeof(node));
    (*node1).data=data;
    (*node1).leftchild = NULL;
    (*node1).rightchild = NULL;
    return node1;
}

void insertIntoBST(struct node** ptrtoroot, struct node** ptrtotemp){
    if((**ptrtotemp).data <= (**ptrtoroot).data){
        if((**ptrtoroot).leftchild != NULL){
            insertIntoBST((*ptrtoroot).leftchild,(*ptrtotemp));
        }
        else{
           (*ptrtoroot->leftchild) = *ptrtotemp;
        }
    }
     if((**ptrtotemp).data > (**ptrtoroot).data){
        if((**ptrtoroot).rightchild != NULL){
            insertIntoBST((*ptrtoroot->rightchild),(*ptrtotemp));
        }
        else{
           (*ptrtoroot->rightchild) = *ptrtotemp;
        }
    }

}

void inorder(struct node* root){
    while(root != NULL){
        cout<<(*root).data;
        inorder((*root).leftchild);
        inorder((*root).rightchild);
    }
}

int main(){
    struct node* root = NULL;
    struct node* temp;
    int dat;
    for(int i = 0 ; i < 6 ; i++){
    cin>>dat;
    temp = newNode(dat);
    if(root == NULL){
        root = temp;
    }
    else{
        insertIntoBST(&root,&temp);
    }
 }
 inorder(root);

    return 0;
}

错误代码:

bst.cpp:21:40: error: request for member ‘leftchild’ in ‘* ptrtoroot’, which is of pointer type ‘node*’ (maybe you meant to use ‘->’ ?)  
21 | insertIntoBST((ptrtoroot).leftchild,(*ptrtotemp));  
   | ^~~~~~~~~ bst.cpp:24:25: error: request for member ‘leftchild’ in ‘ ptrtoroot’, which is of pointer type ‘node*’ (maybe you meant to use ‘->’ ?)  
24 | (*ptrtoroot->leftchild) = *ptrtotemp;  
c++ pointers binary-search-tree
1个回答
0
投票

好吧,我认为您的功能如下所示。

void insertIntoBST(struct node** ptrtoroot, struct node** ptrtotemp){
    if((**ptrtotemp).data <= (**ptrtoroot).data){
        if((**ptrtoroot).leftchild != NULL){
            insertIntoBST((*ptrtoroot).leftchild,(*ptrtotemp));

[ptrtoroot是双指针,即指向指针的指针,因此这使得(* ptrtoroot)成为指针,在这里

(*ptrtoroot).leftchild should be replaced with "->" operator 
like (*ptrtoroot)->leftchild

第二个在递归调用下insertIntoBST函数将双指针作为参数,因此您需要在此处传递指针的地址。

即(* ptrtoroot)-> leftchild从您的节点结构返回的指针的地址。

something like &((*ptrtoroot)->leftchild)

我还没有完全执行您的代码,但是应该可以。

© www.soinside.com 2019 - 2024. All rights reserved.