Tree树

Posted ai-cobe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于Tree树的主要内容,如果未能解决你的问题,请参考以下文章

线段树——入门学习(java代码实现)

DataStructure--Tree--decision tree 决策树

WPF知识点全攻略06-WPF逻辑树(Logical Tree)和可视树(Visual Tree)

字典树

Spark MLlib速成宝典模型篇05决策树Decision Tree(Python版)

算法练习:最小生成树 (Minimum Spanning Tree)