皓月星空

导航

二叉树

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\n",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\n",root->data);
    free(root);
    root = NULL;
    return;
}

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

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


posted on 2021-05-08 19:19  皓月星空  阅读(61)  评论(0编辑  收藏  举报