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 }
  • 相关阅读:
    HDU 1010 Tempter of the Bone(DFS剪枝)
    HDU 1013 Digital Roots(九余数定理)
    HDU 2680 Choose the best route(反向建图最短路)
    HDU 1596 find the safest road(最短路)
    HDU 2072 单词数
    HDU 3790 最短路径问题 (dijkstra)
    HDU 1018 Big Number
    HDU 1042 N!
    NYOJ 117 求逆序数 (树状数组)
    20.QT文本文件读写
  • 原文地址:https://www.cnblogs.com/AI-Cobe/p/9359059.html
Copyright © 2011-2022 走看看