Tree樹
阿新 • • 發佈:2018-07-24
一對多 color stdio.h clu order 存在 pri eth array
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 structtree * 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\n", 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 elseif(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樹