zoukankan      html  css  js  c++  java
  • Tree树

    tree,是非线性数据结构,array、linked list、stack、queue,是线性数据结构。

    线性数据结构:数据元素是一对一

    非线性数据结构:数据元素存在一对多或者多对一的关系

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 
     4 struct tree
     5 {
     6     int data;
     7     struct tree * left;
     8     struct tree * right;
     9 };
    10 struct tree * newNode(int data)
    11 {
    12     struct tree * root = (struct tree *)malloc(sizeof(struct tree));
    13     root->data = data;
    14     root->left = NULL;
    15     root->right = NULL;
    16 
    17     return root;
    18 }
    19 void printLevelOrder(struct tree * root)
    20 {
    21     int height = getHeight(root);
    22 
    23     printf("%d
    ", height);
    24     for(int i = 1; i <= height; i++)
    25     {
    26         printGivenLevel(root, i);
    27     }
    28 }
    29 void printGivenLevel(struct tree * root, int level)
    30 {
    31     if(NULL == root)
    32     {
    33         return ;
    34     }
    35     if(1 == level)
    36     {
    37         printf("%d  ", root->data);
    38     }
    39     else if(level > 1)
    40     {
    41         printGivenLevel(root->left, level-1);
    42         printGivenLevel(root->right, level-1);
    43     }
    44 }
    45 int getHeight(struct tree * root)
    46 {
    47     int lheight = 0;
    48     int rheight = 0;
    49 
    50     if(NULL == root)
    51     {
    52         return 0;
    53     }
    54     else
    55     {
    56         //两个递归有点恶心,头脑混乱的话,最好调试下,屡一下
    57         lheight = getHeight(root->left);
    58         rheight = getHeight(root->right);
    59 
    60         if(lheight > rheight)
    61         {
    62             return (lheight + 1);
    63         }
    64         else
    65         {
    66             return (rheight + 1);
    67         }
    68     }
    69 }
    70 int main(void)
    71 {
    72     struct tree * root = newNode(1);
    73     root->left = newNode(2);
    74     root->right = newNode(3);
    75     root->left->left = newNode(4);
    76     root->left->right = newNode(5);
    77 
    78     printLevelOrder(root);
    79     return 0;
    80 }
  • 相关阅读:
    new Date(str)返回 Invalid date问题
    时间倒计时
    js返回上一页并刷新 代码整理
    赋值变量值在标签里
    jQuery获取select选择的文本与值
    判断div里面的子集是否含有特定的类
    卷boot仅剩余XX空间
    ubuntu16.04 anaconda3安装
    ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061)
    毕业设计
  • 原文地址:https://www.cnblogs.com/AI-Cobe/p/9359059.html
Copyright © 2011-2022 走看看