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

版权声明:本文为博主原创文章,未经博主允许不得转载,如果有错误,欢迎指正,提前感谢。 https://blog.csdn.net/Quinlan_/article/details/88076267

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

#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;
}

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

猜你喜欢

转载自blog.csdn.net/Quinlan_/article/details/88076267
今日推荐