首页 > 其他 > 详细

二叉树

时间:2021-05-08 22:46:21      阅读:27      评论:0      收藏:0      [点我收藏+]

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

技术分享图片

二叉树

原文:https://www.cnblogs.com/hyxk/p/14746235.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!