二叉树的性质(2)

今天继续学习了二叉树的性质,今天学习的性质没有昨天的多,还有就是,作业题的解题思路我也写在博客里吧!

一、查找二叉树中的结点

这里要注意:每次返回之后,如果没有接收,那么返回的值会被丢弃。

BTNode* BinaryTreeFind(BTNode* root, BTDataType x)
{
    if(root == NULL)
    {
        return NULL;
    }
    if(root->data == x)
    {
        return root;
    }
    BTNode* ret1 = BinaryTreeFind(root->left,x);
    if(ret1)
        return ret1;
    BTNode* ret2 = BinaryTreeFind(root->right,x);
    if(ret2)
        return ret2;
    return NULL;
}

下面是我画的图解:递归的过程

二、判断两棵树是不是相同,结构和结点值都一样

bool isSameTree(BTNode* root1, BTNode* root2)
{
    if(root1 ==NULL && root2==NULL)
    {
        reutrn true;
    }
    //特别注意,这里的两个if是不能换顺序的
    if(root1==NULL || root2==NULL)//这个判断是考虑到上图中第二幅图的情况
        return false;
    if(root1->data != root2->data)
    {
        return false;
    }
    return isSameTree(root1->left,root2->left)&&isSameTree(root1->right,root2->right);
}

三、判断一棵树是不是单树

单树的意思是:每一个结点的值都是相等的

bool SimpleTree(BTNode* root)
{
    if(root==NULL)
        return ture;
    if(root->left && root->left->data != root->data)
        return false;
    if(root->right && root->right->data != root->data)
        return false;
    return SimpleTree(root->left) && SimpleTree(root->right); 
}

四、将一个数组里的元素按照先序遍历放入二叉树,然后再用中序遍历打印出来

BTNode* rebulidTree(char* str, int* i)
{
    if (str[*i] == '#')
    {
        (*i)++;
        return NULL;
    }
    BTNode* root = (BTNode*)malloc(sizeof(BTNode));
    if (root == NULL)
    {
        return;
    }
    root->data = str[(*i)++];
    root->left = rebulidTree(str, i);
    root->right = rebulidTree(str, i);

    return root;
}
BTNode* inOrder(BTNode* root)
{
    if (root == NULL)
    {
        return;
    }
    inOrder(root->left);
    printf("%c", root->data);
    inOrder(root->right);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Though even

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值