怎样编写一个程序,把一个有序整数数组放到二叉树中?

本文介绍如何将有序整数数组转换为二叉搜索树的递归算法实现。通过中间元素作为根节点,左右两侧子数组分别构建左子树和右子树,最终形成平衡的二叉搜索树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

怎样编写一个程序,把一个有序整数数组放到二叉树中?
分析:本题考察二叉搜索树的建树方法,简单的递归结构。
关于树的算法设计一定要联想到递归,因为树本身就是递归的定义。



#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

struct btree {
    struct btree *left;
    struct btree *right;
    int value;
};

void create_btree(struct btree **rt, int *arr, int r, int l)
{
    int pos;
    struct btree *root;
    if (r > l) {
        *rt = NULL;
        return;
    }
    pos = (r + l) / 2;
    root = (struct btree *)malloc(sizeof(struct btree));
    assert(root != NULL);
    root->value = arr[pos];
    *rt = root;
    create_btree(&(root->left), arr, r, pos - 1);
    create_btree(&(root->right), arr, pos + 1, l);
}


int A[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
/*
 *                5
 *            3            8
 *
 */

void display_btree(struct btree *root)
{

    if (root == NULL) {
        return;
    }
    display_btree(root->left);
    printf("%d ", root->value);
    display_btree(root->right);
}
int main()
{
    struct btree *root = NULL;
    create_btree(&root, A, 0, 9);
    printf("----------------------\n");
    display_btree(root);
    printf("\n----------------------\n");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值