二级指针创建二叉树节点与一级指针创建二叉树节点

 1、c++中的struct结构体变量定义 可以直接 “类型名 变量名”,c中只能 “struct 类型名 变量名” ,可以通过typedef 达到相同的效果;

   struct _x1 { ...}x1; 是定义了类_x1和_x1的对象实例x1,

  typedef struct _x2{ ...} x2;  定义了类_x2和_x2的类别名x2 ;

  typedef struct {int num;int age;}aaa,bbb,ccc;相当于三个类型别名;

2、二级指针:p置空,p的值 (nullptr) 其实就是0;但是p本身是一个变量,仍然具有地址,二级指针指向p;

#include <bits/stdc++.h>
using namespace std;
int main(){

    int* p = nullptr;
    int**p1 = nullptr;
    p1 = &p;
    cout << p << endl;
    cout << p1 << endl;
    system("pause");
    return 0;
}

/*
0
0x61ff08
*/

反例:调用函数并没有改变p值;

#include <bits/stdc++.h>
using namespace std;

void first__ptr(int *ptr){
    ptr = new int(100);
    cout << ptr << endl;
    delete ptr;
}

int main(){
    int* p = nullptr;
    cout << p << endl;
    first__ptr(p);
    cout << p << endl;
    system("pause");
    return 0;
}
/*
0
0xd318b0
0
*/

修改:通过传递二级指针,操作*ptr达到修改p的值;

#include <bits/stdc++.h>
using namespace std;

void first__ptr(int *ptr){
    ptr = new int(100);
    cout << ptr << endl;
    delete ptr;
}
void second_ptr(int **ptr){
    *ptr = new int(100); 
    cout << *ptr << endl;
    delete ptr;
}

int main(){
    int* p = nullptr;
    int** p1 = &p;
    cout << p << endl;
    second_ptr(p1);
    cout << p << endl;
    system("pause");
    return 0;
}
/*
0
0x1e18b0
0x1e18b0
*/

3、创建二叉树节点时使用二级指针(参考二叉树创建为什么用二级指针 - Pearl_zju - 博客园 (cnblogs.com) )

首先是二叉树创建需要使用指针代表节点的缘故,达到链表的效果;也就是每个节点自身就是个一级指针;

个人总结:要使用一级指针的话:递归函数形参是一级指针,但是得有返回值,也是一级指针,函数中操作的是指针本身,返回值也是指针本身;Node* createNode(Node* node) ; 

     要使用二级指针的话:递归函数形参是二级指针,但是不需要返回值; 函数中操作的是*node1,即操作一级指针变量的值,void createNode(Node ** node1);

因为一级指针传递进去的是值传递,不影响调用者的值;但是可以通过函数返回值赋值给调用者,达到改变原值的效果;二级指针是一级指针变量的地址,那么操作*node1,也就是在操作一级指针;

这儿可以理解为:将节点和二级指针都降一级; 节点自身相当于一个 int a变量,二级指针相当于一级指针 int*p = &a,那么要想在另一个函数中改变a的值,传参的时候就需要传递变量a的地址,操作*p就相当于改变a的值,函数也不需要返回值就能改变原值了;

代码实现

#include <bits/stdc++.h>
using namespace std;

typedef struct Node{
    int data;
    Node* left, *right;
}Node,*Tree;

/*二级指针*/
void Create(Tree* T){
    int num;
    /*CTRL + Z 结束*/
    if(cin >> num){
        *T = new Node();
        (*T)->data = num;
        Create(&((*T)->left));
        Create(&((*T)->right));
    }
}
/*一级指针*/
Tree create1(Tree T){
    int num;
    if(cin >> num){
        T = new Node();
        T->data = num;
        T->left = create1(T);
        T->right = create1(T);
    }else{
        T = nullptr;
    }
    return T;
}
void preorder(Tree T){
    if(T == nullptr){
        return;
    }
    cout << T->data << "\t";
    preorder(T->left);
    preorder(T->right);
}

int main(){
    Tree T;
    cout << "put in binary tree:" << endl;
    //Create(&T);
    T = create1(T);
    preorder(T);

    cout << endl;
    system("pause");
    return 0;
}
/*
put in binary tree:
7 2 10  1 3 8 11^Z
7       2       10      1       3       8       11
*/

 

posted @ 2023-04-12 13:21  QianFa01  阅读(122)  评论(1)    收藏  举报