建立搜索二叉树BST(HDU---3999)

主要是创建的时候要为空节点动态分配再赋值,不然没有儿子,必须得有儿子,哪怕为空,不然不是叶子节点,不然输出遍历的时候会错!(传头结点参数的时候传它的地址,因为这样方便改变)

#include <bits/stdc++.h>

using namespace std;

typedef struct tree {
    tree* left;
    tree* right;
    int data;
}* ptree;


ptree fathertree;

ptree createtree(int data, ptree &root) {	//传引用,通过改变指针变量指向的地址来改变指针变量的值
    if (root == nullptr) {
        ptree t = new tree; //这里必须动态分配,不然函数调用完就释放没了,也要想象一下,每个空节点赋值自己多了两个儿子,不然没有儿子
        t->data = data;
        t->left = nullptr;
        t->right = nullptr;
        return t;
    }
    else if (data < root->data) {
        root->left = createtree(data, root->left);
    }
    else if (data > root->data) {
        root->right = createtree(data, root->right);
    }
    return root;    //走到底后或者data值相等就直接返回啦!千万不要忘了!
}

void print(ptree now) {
    if (now != nullptr) {
        if (now == fathertree) {
            printf("%d",now->data);
        }
        else
            printf(" %d",now->data);
        print(now->left);
        print(now->right);
    }
}
int main()
{
    int N;
    while(~scanf("%d",&N)) {
        int t;
        fathertree = nullptr;
        while(N--) {
            scanf("%d", &t);
            fathertree = createtree(t, fathertree);
        }
        print(fathertree);
        printf("\n");
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值