在計算機科學中,樹是一種重要的非線性數據結構,直觀地看,它是數據元素(在樹中稱爲結點)按分支關係組織起來的結構。二叉樹是每一個節點最多有兩個子樹的有序樹。一般子樹被稱做「左子樹」(left subtree)和「右子樹」(right subtree)。二叉樹常被用於實現二叉查找樹和二叉堆。node
以下是實現建立二叉樹和二叉樹中序遍歷的代碼:數據結構
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <memory.h> 4 5 typedef struct _tree_node{ 6 char data; 7 struct _tree_node * left; 8 struct _tree_node * right; 9 struct _tree_node * father; 10 }tree_node; 11 12 void createTree(tree_node * root); 13 void inorderTraverseTree(tree_node * pRoot); 14 15 int main() 16 { 17 tree_node root; 18 memset(&root, 0 , sizeof(tree_node)); 19 printf("Please create the tree: \n"); 20 createTree(&root); 21 printf("The inorder traverse result is: \n"); 22 inorderTraverseTree(&root); 23 return 0; 24 } 25 26 //inorder traversal 27 void inorderTraverseTree(tree_node * pRoot) 28 { 29 tree_node * pCur = pRoot; 30 if(pCur != NULL) 31 { 32 if(pCur->left != NULL) 33 { 34 inorderTraverseTree(pCur->left); 35 } 36 else 37 { 38 printf("%c ", pCur->data); 39 return; 40 } 41 printf("%c ", pCur->data); 42 43 if(pCur->right != NULL) 44 { 45 inorderTraverseTree(pCur->right); 46 } 47 } 48 } 49 50 //Create the binary tree 51 void createTree(tree_node * pRoot) 52 { 53 char ch = 0; 54 tree_node * pCur = pRoot; 55 while((ch = getchar())!= 'e') 56 { 57 //printf("%c" , ch); 58 tree_node * pNewNode = (tree_node *)malloc(sizeof(tree_node)); 59 pNewNode->left = NULL; 60 pNewNode->right = NULL; 61 pNewNode->father = NULL; 62 if(ch == 'L') 63 { 64 //printf("Input L\n"); 65 pNewNode->data = getchar(); 66 pNewNode->father = pCur; 67 pCur->left = pNewNode; 68 pCur = pNewNode; 69 } 70 else if(ch == 'R') 71 { 72 //printf("Input R\n"); 73 pNewNode->data = getchar(); 74 pNewNode->father = pCur; 75 pCur->right = pNewNode; 76 pCur = pNewNode; 77 } 78 else if(ch == 'B') 79 { 80 //printf("Input B\n"); 81 free(pNewNode); 82 if(pCur->father != NULL) 83 pCur = pCur->father; 84 else 85 printf("It's the top\n"); 86 } 87 } 88 }
構造這樣一顆二叉樹:spa
程序運行結果爲:code