zoukankan      html  css  js  c++  java
  • C语言 二叉树的创建以及中序遍历的排序问题

    在编写下列代码的前提是所有插入的元素均为正整数,求每个数字都是不相同的

    今天学习的是二叉树的创建

    在创建过程中发现中序遍历能够讲原先无序的数组转换成有序数组输出

    具体讲解将在这几天写完

    考虑到二叉树的具体一些操作会用到递归算法

    后期也会考虑加上递归操作的方法

    #include<stdio.h>
    #include<stdlib.h>
    
    typedef struct node{
        int data;
        struct node *right;
        struct node *left;
    }Node;
    typedef struct{
        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(value<temp->data)
                {
                    if(temp->left==NULL)
                    {
                        temp->left=node;
                        break;                    
                    }
                    else
                        temp=temp->left;
                }
                if(value>temp->data)
                {
                    if(temp->right==NULL)
                    {
                        temp->right=node;
                        break;
                    }
                    else
                        temp=temp->right;
                }
            }
        }
    }
    
    void preorder(Node *node)
    {
        if(node!=NULL)
        {
            printf("%d	",node->data);
            preorder(node->left);
            preorder(node->right);
        }
    }
    
    void inorder(Node *node)
    {
        if(node!=NULL)
        {
            inorder(node->left);
            printf("%d	",node->data);
            inorder(node->right);
        }
    }
    
    int depth(Node *node)
    {
        if(node==NULL)
            return 0;
        else
        {
            int ld=depth(node->left);
            int rd=depth(node->right);
            return (ld>rd?ld:rd)+1;
        }
    }
    
    int main(){
        Tree tree;
        tree.root=NULL;
        int value[9]={5,4,7,8,9,2,1,3,10};
        for(int i=0;i<9;i++)
            insert(&tree,value[i]);
        printf("中序遍历的结果为:
    
    "); 
        inorder(tree.root);
        printf("
    
    ");
        int dp=depth(tree.root);
        printf("深度为%d
    ",dp);
    }
  • 相关阅读:
    调整压力测试工具转载ibm
    Python装饰器的使用
    python操作mysql数据库
    python进程与线程的操作
    python selenium框架的Xpath定位元素
    在Ubuntu Server 12.04 x64下安装Graphite
    SQLCLR(一)入门
    DataSet操作
    ASP.NET传递中文参数乱码的解决方法
    c#.net常用函数和方法集
  • 原文地址:https://www.cnblogs.com/oldfish123/p/12940656.html
Copyright © 2011-2022 走看看