鱼C论坛

 找回密码
 立即注册
查看: 2759|回复: 0

[技术交流] 关于二叉树

[复制链接]
发表于 2018-6-28 16:01:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
最近几天在研究数据结构,由于是新手,二叉树搞了好长时间,中间也出了很多问题,不过最终还是解决了。
这里给大家分享一下我在学习二叉树的一些经验和教训。
#include <iostream>
#include <cstdlib>

using namespace std;

typedef struct BinaryTree
{
    char Data;
    struct BinaryTree* leftchild;
    struct BinaryTree* rightchild;
} BT, *P_bt;  //定义节点结构体,储存节点数据,以及左右节点的地址

void CreatBtree(P_bt troot);   //创建二叉树,设置根节点为空
void AddData(P_bt &troot);   //添加节点数据
void Outlook(P_bt troot);   //遍历二叉树
void Delete(P_bt* troot);   //删除二叉树

int main()
{
    system("color 3F");
    BT Bt;;
    P_bt bt=&Bt;
    //P_bt bt_true=bt;
    CreatBtree(bt);
    AddData(bt);
    Outlook(bt);
    Delete(&bt);

    cout<<"success"<<endl;

    return 0;
}

void CreatBtree(P_bt troot)
{
    troot=NULL;
}

void AddData(P_bt &troot)
{
    char temp;
    cout<<"请输入数据:"<<endl;
    cin>>temp;
    if(temp=='#')
    {
        troot=NULL;
    }
    else
    {
        troot=new BT;   //这里实际上已经对指针本身进行了操作,如果不是传的二级指针或者引用,则根本没用!
        troot->Data=temp;
        AddData(troot->leftchild);
        AddData(troot->rightchild);
    }

}

void Outlook(P_bt troot)
{
    if(troot!=NULL)
    {
        cout<<troot->Data;
        Outlook(troot->leftchild);
        Outlook(troot->rightchild);
    }
}

void Delete(P_bt* troot)
{
    if((*troot)!=NULL)
    {
        Delete(&(*troot)->leftchild);
        Delete(&(*troot)->rightchild);
    }
    else
    {
        delete (*troot);
    }
}

这是正确的结构,不过在很长一段时间我并没有写出正确的代码,其中前最主要的的原因不是不理解二叉树的递归特点,而是我没有用好指针。
我的原始代码的数据输入函数void AddData(P_bt &troot);  是声明为void AddData(P_bt troot);  我传入了一个根节点的指针。
在初次接触指针的时候, 我们就知道swap(int a, int b); 这样的传值并不能最终改变a, b的值,要解决可以使用传址操作,swap(int* a, int* b);
这样就是彻底改变了a, b的值。同理我们在传入地址也就是指针给函数的时候,的确可以改变指针所指的地址的值,但是无法改变指针本身的值,
也就是说,我们在函数里面对指针的解引用操作是有效的,而对指针本身的赋值是无效的。
而此处的函数确实是要改变指针本身,例如new一个节点将其赋给指针,就已经对指针本身进行了操作,但这种影响无法传到函数外。所以我们
可以直接传指针的引用或者二级指针来操作。
哎哎哎,指针还是博大精深!!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 12:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表