第九章 ALDS1_8_A:Binary Search Tree I 二叉搜索树--插入

知识点

二叉搜索树:设x为二叉搜索树的结点,如果y为x的左子树中的结点,那么y的值小于等于x;同理,若在x的右子树,则y的值大于等于x。

问题链接

ALDS1_8_A:Binary Search Tree I

问题内容

insert是插入操作,print是输出中序和前序遍历结果的操作

思路

按照题目的伪代码提示去构建,前序中序遍历用前面的例子代码即可。

代码

#include<iostream>
#include<cstdio>
using namespace std;
const int MAX = 100005;
struct Node {
    int key;
    Node *parent, *left, *right;
};
Node *root, *NIL;

//前序排序
void PreorderTreeWalk(Node *u) {
    if (u == NIL)
        return;
    printf(" %d", u->key);
    PreorderTreeWalk(u->left);
    PreorderTreeWalk(u->right);
}
//中序排序
void InorderTreeWalk(Node *u) {
    if (u == NIL)
        return;
    InorderTreeWalk(u->left);
    printf(" %d", u->key);
    InorderTreeWalk(u->right);
}


void insert(int value) {
    Node *y = NIL, *x = root;
    Node *z = new Node();
    z->key = value;
    z->left = z->right = NIL;

    // 从根结点往下遍历
    while (x != NIL) {
        y = x;
        // z 比 x 小, 则从x的左侧遍历
        // z 比 x 大, 则从x的右侧遍历
        if (z->key < x->key)
            x = x->left;
        else
            x = x->right;
    }

    z->parent = y;

    // 没有父结点的是root
    if (y == NIL) {
        root = z;
    }else {
        // z 比 y 小, 则在y的左侧
        // z 比 y 大, 则在y的右侧
        if (z->key < y->key)
            y->left = z;
        else
            y->right = z;
    }
}


int main() {
    int n, value;
    char s[200];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%s", s);
        if (s[0] == 'i') {
            scanf("%d", &value);
            insert(value);
        }else {
            InorderTreeWalk(root);
            printf("\n");
            PreorderTreeWalk(root);
            printf("\n");
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值