zoukankan      html  css  js  c++  java
  • c语言数据结构分析4之 树

     1 #include "stdafx.h"
    2 #include <stdlib.h>
    3 struct tree{
    4 char info;
    5 struct tree* left;
    6 struct tree* right;
    7 };
    8 struct tree* root;
    9 struct tree* construct(struct tree* root,struct tree* insert,char info);
    10 void print(struct tree* root,int n);
    11
    12 int main(int argc, char* argv[])
    13 {
    14 root=NULL;
    15 char s[10];
    16 do
    17 {
    18 printf("input str\n");
    19 gets(s);
    20 root=construct(root,root,*s);
    21 } while (*s);
    22
    23 print(root,0);
    24
    25 return 0;
    26 }
    27
    28 struct tree* construct(struct tree* root,struct tree* insert,char info)
    29 {
    30 //root 为父根,insert 为子根,info为插入的内容
    31 if(!insert) //insert 当为父根时,创建
    32 {
    33 insert=(struct tree*)malloc(sizeof(struct tree));
    34 insert->info=info;
    35 insert->left=NULL;
    36 insert->right=NULL;
    37 if(!root) return insert; //第一次创建时,根初始化 insert 就是 root根
    38 if(info < root->info) //两字符相比,是比指针地址,谁先申请地址谁最大
    39 root->left=insert;
    40 else
    41 root->right=insert;
    42 }else{ //否则就不是父根 就要递归创建
    43 if(info< root->info)
    44 construct(insert,insert->left,info);
    45 else
    46 construct(insert,insert->right,info);
    47 }
    48 return root;
    49 }
    50
    51 void print(struct tree* root,int n) //n 是添加多少个空格
    52 {
    53 if(!root) return;
    54 print(root->left,n+1);
    55
    56 for(int i=0;i<n;i++)
    57 printf(" ");
    58
    59 printf("%c\n",root->info);
    60
    61 print(root->right,n+1);
    62 }

      

  • 相关阅读:
    LG P4284 [SHOI2014]概率充电器
    LG P2592 [ZJOI2008]生日聚会
    LG P4953 [USACO02FEB]Cow Cycling
    LG P2389 电脑班的裁员
    LG P2344 [USACO11FEB]Generic Cow Protests G
    前端简历
    前端面试题目
    大前端的技术栈
    前端 -为什么要清楚浮动?
    Redis的功能实现
  • 原文地址:https://www.cnblogs.com/solq/p/2138431.html
Copyright © 2011-2022 走看看