4 The family tree of Sigmund Christoph von

































- Slides: 33
4 樹 The family tree of Sigmund Christoph von Waldburg-Zeil-Trauchburg http: //www. ahneninfo. com/de/ahnentafel. htm
6 樹的字典 • Root A • Node • Degree B • Leaf • Terminal nodes E • Children • Siblings • Degree of a tree • Ancestors • Level • Height or Depth K F L D C G H M I J
7 怎麼在記憶體裡面記一棵樹呢? Data Child 1 • A 1 B … k 2 C Child 2 … ㄅ Child 3 … Child k
9 來畫一下 怎麼用LC-RS表示這棵樹? A B E K D C F L A G H M B I J E K F L D C G H M I J
11 Binary Tree • Definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree. • 注意: 可以是沒有node • 比較: 一般tree不可以沒有node • 注意: children在左邊或右邊是不一樣的 (有順序) • 比較: 一般tree的children順序沒有差
15 Full binary tree • 1 3 2 4 5 6 7 depth=3的full binary tree
16 Complete binary tree • Definition: A binary tree with n nodes and depth k is complete iff its nodes correspond to the nodes numbered from 1 to n in the full binary tree of depth k. 1 2 4 1 3 5 Yes 3 2 4 5 Yes 4 Yes 3 2 2 2 6 1 1 1 5 No 5 6 No
17 Complete binary tree的高度 •
21 如何在記憶體裡面表示binary tree? data • 方法 2: Linked Representation Data left child right child left child • 每個node都用malloc拿一塊新的 • 如果需要找到parent, 可以加一個新的欄位parent root left B right A right left C right child
23 Binary Tree Traversal • 如果L一定要在R之前, 那麼有三種 • VLR: preorder 雍穎 • LVR: inorder • LRV: postorder 昱廷 雅喬 立中 偉誠 • 請同學說明preorder, inorder, postorder traversal分別順序是 如何
24 Binary tree with arithmetic expression • 每個arithmetic expression都可以建立一個expression tree • Preorder prefix * • Inorder infix • Postorder postfix - • 請同學試試看 • (亂寫一個expression看看) 2 3 5
25 Binary Tree Traversal • 可以用recursive寫法來做traversal (會很簡潔): void inorder(tree. Pointer ptr) { inorder(ptr->left. Child); visit(ptr); inorder(ptr->right. Child); }
26 那如果不要用recursive寫法呢? • 用Stack for(; ; ) { for(; node=node->left. Child) push(node); node=pop(); if (!node) break; printf(“%d”, node->data); node=node->right. Child; }
27 Level-order traversal • 如果改成用queue呢? add(ptr); for(; ; ) { ptr=delete(); if (ptr) { printf(“%d”, ptr->data); if (ptr->left. Child) add(ptr->left. Child); if (ptr->right. Child) add(ptr->right. Child); } else break; }
28 Priority Queues • 一種每次都可以拿到priority最高的element的queue • 直接來定義operations • Push(element) 把element放進queue裡面 • Pop() 把element拿出來. 這個element有最高的priority • (可以想像, 放進去的時候有做一些排序) • 另外也有empty, full等等的operation • 請同學想想看, 要怎麼用已經學過的東西來做priority queue? • Linked List?
29 Heap • Definition: A max tree is a tree in which the key value in each node is no smaller (larger) than the key values in its children (if any). • Definition: A max heap is a complete binary tree that is also a max tree. A min heap is a complete binary tree that is also a min tree. 14 • 有了heap, 我們要怎麼用它來 做priority queue? • Root是不是永遠都是最大? 12 10 8 7 6
32 Heap • Time complexity是多少? ? • Push operation = O(? ? ) • Pop operation = O(? ? )

































