zoukankan      html  css  js  c++  java
  • 二叉树

    1.二叉树的遍历

    前序 :先遍历根节点(父母节点),然后遍历左孩子 , 最后遍历右孩子。
    中序 :先遍历左孩子, 然后遍历根节点 , 最后遍历右孩子 。
    后序 :先遍历左孩子, 然后遍历右孩子,之后遍历根节点
    按层 :按树的每一层来遍历(高度)兄弟节点(使用队列来实现)

    2.二叉树的节点设计


    typedef struct tree
    {
        int data;
        struct tree *R, *L;
    }Tree, *P_Tree;
    

    3.简单的二叉树的实现

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //定义二叉树
    typedef struct tree
    {
        int data;
        struct tree *R, *L;
    }Tree, *P_Tree;
    
    P_Tree tree_init(int data)
    {
        P_Tree new = calloc(1,sizeof(Tree));
        new->data = data;
    
        new->L = new->R = NULL;
        return new;
    }
    
    int get_user_input() 
    {
        int num = 0;
        printf("请输入整数:");
        scanf("%d",&num);
        return num;
    }
    
    P_Tree add_new_tree(P_Tree root,P_Tree new)
    {
        if(root == NULL)
        {
            
            return new;
        }
        if(root->data > new->data)
        {
            root->L = add_new_tree(root->L,new);
            
        }
        else
        {
            root->R = add_new_tree(root->R,new);
            
        }
        return root;
    }
    
    void tree_display(P_Tree root)
    {
        if(root == NULL)
        {
            return;
        }
        tree_display(root->L);
        printf("%d
    ",root->data);
        tree_display(root->R);
    
    }
    
    int main(int argc, char const *argv[])
    {
        //初始化,创建头结点
        P_Tree root = tree_init(50);
        //添加新二叉树值
        for(int i = 0; i < 5;i++)
        {
            //获取输入值      
            int data  = get_user_input();
    
            //创建新节点
            P_Tree new  = tree_init(data);
            
            //将新节点添加进入树中
            root = add_new_tree(root,new);
        }
        //显示二叉树
        
        tree_display(root);
    
        return 0;
    }
    
    

    4.二叉树的销毁

    销毁二叉树,要从叶子开始销毁

    void destory_tree(P_Tree root)
    {
        if(root == NULL)
        {
            return;
        }
        destory_tree(root->L);
        destory_tree(root->R);
        printf("删除节点有:%d
    ",root->data);
        free(root);
        root = NULL;
        return;
    }
    

    5.删除二叉树的某一个节点

    要删除某一个节点,需要注意的是要找到该节点的左右两个子节点,找到左边的最大值或者是右边的最小值来替换删除的节点

    
    
  • 相关阅读:
    (2)远程管理线上服务之sshd服务
    (1)远程管理线上服务之sshd服务
    自建yum仓库
    CentOS7安装MySQL报错Failed to start mysqld.service: Unit not found解决办法
    ssh(Spring,Struts2,Hibernate)注解版整合
    Hibernate关联映射(多对一,一对多, 一些属性(Cascade,inverse,order by))
    HQL查询(分页查询,动态sql查询,参数查询)
    初识Oracle
    ajax获取属性值
    关于SpringMvc返回值类型 Object使用
  • 原文地址:https://www.cnblogs.com/hyxk/p/14746235.html
Copyright © 2011-2022 走看看