Tree Binary Tree Binary Search Tree 2 Tree
大綱 樹 (Tree) 二元樹 (Binary Tree) 二元搜尋樹 (Binary Search Tree) 2
大綱 樹 (Tree) 二元樹 (Binary Tree) 二元搜尋樹 (Binary Search Tree) 8
二元樹鏈結表示法 二元樹節點鏈結表示法 struct binary_tree_node { 資料型態 變數名稱; struct binary_tree_node *left; struct binary_tree_node *right; }; typedef struct binary_tree_node; node *root; root = (node *)malloc(sizeof(node)); root ->left= NULL; root ->right= NULL; node * root node 資料 left NULL right (malloc) 11
二元樹的走訪種類 中序走訪(Inorder Traversal)。 void print_inorder(node *ptr) { if(ptr != NULL) { print_inorder(ptr->left); printf("[%2 d]n", ptr->data); print_inorder(ptr->right); } } 中序: 1, 2, 3, 4, 5, 6, 7, 8, 9 15
練習 前序走訪(Preorder Traversal)。 void print_preorder(node *ptr) { if(ptr != NULL) { // 前序: 5, 4, 2, 1, 3, 6, 8, 7, 9 } } 後序走訪(Postorder Traversal)。 void print_postorder(node *ptr) { if(ptr != NULL) { // 後序: 1, 3, 2, 4, 7, 9, 8, 6, 5 } } 16
二元樹的搜尋 利用二元樹走訪實作二元樹的搜尋 node *search. Node(node *ptr, int value) { node *temp; if(ptr != NULL) { if(ptr->data == value) return ptr; else { temp = search. Node(ptr->left, value); if(temp != NULL) return temp; temp = search. Node(ptr->right, value); if(temp != NULL) return temp; } } return NULL; } 8 17
大綱 樹 (Tree) 二元樹 (Binary Tree) 二元搜尋樹 (Binary Search Tree) 18
二元搜尋樹: 插入 node *insert. Node(node *root, node data) { node *new_node; node *current; node *parent; // 建立節點 new_node = (node *)malloc(sizeof(node)); *new_node = data; if(root == NULL) // 目前無資料 return new_node; else { current = root; // 從頭找要新節點之插入點 while(current != NULL) { parent = current; // 找新節點之父節點 if(current->data > new_node->data) current = current->left; // 往左找 else current = current->right; // 往右找 } if(parent->data > new_node->data)// 插入此父節點左邊或右邊 parent->left = new_node; else parent->right = new_node; } return root; // 回傳此樹 } 18 10 5 1 20 8 15 30 18 20
二元搜尋樹: 搜尋 利用資料的排列特性可以快速搜尋到資料 比較:一般二元樹的搜尋 node *search. Node(node *root, int value) { node *ptr = root; while(ptr != NULL) { if(ptr->data == value) // 找到目標 return ptr; // 回傳此節點 else { if(ptr->data > value) ptr = ptr->left; // 往左找 else ptr = ptr->right; // 往右找 } } return NULL; // 找不到 } 10 5 1 20 8 15 30 21
- Slides: 30