二叉搜索树 插入,得到高度和最大值C语言实现

本文介绍了二叉搜索树的基本特性,即小元素在左,大元素在右。强调了在二叉树操作中递归思想的重要性,并未展示具体的C语言代码实现,用于在二叉搜索树中进行插入操作以及如何获取树的高度和最大值。

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

***二叉搜索树***的结构,首先是一个二叉树,特点是小的元素放在左边,大的元素放在右边。代码如下

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

typedef struct node {
    struct node *left;
    struct node *right;
    int data;
} Node;

typedef struct tree {
    Node *root;
} Tree;

void insert(Tree *tree, int value)
{
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = value;
    node->left = NULL;
    node->right = NULL;

    if( tree->root == NULL )
    {
        tree->root = node;
    }
    else
    {
        Node *temp = tree->root;
        while( temp != NULL )
        {
            if( temp->data < value )
            {
                if( temp->right == NULL )
                {
                    temp->right = node;
                    return;
                }
                else
                {
                    temp = temp->right;
                }
            }
            else
            {
                if( temp->left == NULL )
                {
                    temp->left = node;
                    return;
                }
                else
                {
                    temp = temp->left;
                }
            }
        }
    }
}

void inOrder(Node *node)
{
    if( node != NULL )
    {
        inOrder(node->left);
        printf("%d\n", node->data);
        inOrder(node->right);
    }
}

int getHeight(Node *node)
{
    if( node == NULL )
    {
        return 0;
    }
    else
    {
        int left_h = getHeight(node->left);
        int right_h = getHeight(node->right);
        int max = left_h;
        if( max < right_h )
        {
            max = right_h;
        }
        return max+1;
    }
}

int getMax(Node *node)
{
    if( node == NULL )
    {
        return -1;
    }
    else
    {
        int root_m = node->data;
        int left_m = getMax(node->left);
        int right_m = getMax(node->right);
        int max = root_m;
        if( left_m > max )
        {
            max = left_m;
        }
        if( right_m > max )
        {
            max = right_m;
        }
        return max;
    }
}

int main()
{
    int arr[7] = {5, 1, 3, 2, 9, 6, 4};
    Tree tree;
    tree.root = NULL;
    for(int i=0; i<7; i++)
    {
        insert(&tree, arr[i]);
    }

    inOrder(tree.root);

    int height = getHeight(tree.root);
    printf("height: %d\n", height);

    int max = getMax(tree.root);
    printf("max: %d\n", max);
    return 0;
}

二叉树中,递归是个很重要的思想,用的很多。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值