960 likes | 1.26k Views
Data Structures. Chapter 5: Trees. Trees. Definition: A tree is a finite ( 有限的 ) set of one or more nodes such that: There is a specially designated node called the root ( 樹根 )
E N D
Data Structures Chapter 5: Trees
Trees Definition: A tree is a finite (有限的) set of one or more nodes such that: There is a specially designated node called the root (樹根) The remaining nodes are partitioned into n 0 disjoint(無交集的) setsT1, …, Tn, where each of these sets is a tree. We call T1, …, Tn the subtrees(子樹) of the root.
Pedigree Genealogical Chart 血統、家譜 宗譜的、家系的 圖 Cheryl Rosemary Kevin Kelly Richard John Terry Jack Anthony Michelle Mary Karen Joe Mike Angela Binary Tree
Lineal Genealogical Chart 直系的、世襲的 宗譜的、家系的 圖 Proto Indo-European Italic Hellenic Germanic Osco-Umbrian Latin Greek North Germanic West Germanic Osco Umbrian Spanish French Italian Icelandic Norwegian Swedish Low High Yiddish
Tree Terminology Normally we draw a tree with the root at the top. The degree (分支度) of a nodeis the number of subtrees of the node. The degree of a tree is the maximum degree of the nodes in the tree. A node with degree zero is a leaf(葉子) or terminal(終端)node. A node that has subtrees is the parent of the roots of the subtrees, and the roots of the subtrees are the children of the node. Children of the same parents are called siblings (兄弟). A B C D E F G H I J K L M
Tree Terminology (Cont.) The ancestors(祖先) of a node are all the nodes along the path from the root to the node. The descendants(後代) of a node are all the nodes that are in its subtrees. Assume the root is at level 1, then the level(階層) of a node is the level of the node’s parent plus one. The height(高度) or the depth(深度)of a tree is the maximum level of any node in the tree. A B C D E F G H I J K L M
A Sample Tree A B C D E F G H I J K L M root degree(A) = 3 degree(B) = 2 degree(T) = 3 Level height(T) = depth(T) = 4 1 2 3 4 leaf nodes (terminal nodes) = {K, L, F, G, M, I, J}
List Representation of Trees A B C D E F G H I J K L M The tree in previous slide could be written as (A (B (E (K, L), F), C(G), D(H (M), I, J))) A 0 B F 0 C G 0 D I J 0 E K L 0 H M 0
Possible Node Structure for a Tree of Degree k Lemma 5.1: If T is a k-ary tree (i.e., a tree of degree k) with n nodes, each having a fixed size as in Figure 5.4, then n(k1) + 1 of the nk child fields are 0, n 1. Data Child 1 Child 2 Child 3 Child 4 … Child k Wasting memory! A B C D E F n = 6, k = 3
Representation of Trees Left Child-Right SiblingTree 左子右兄弟 Each node has two links (or pointers) Each node only has one leftmost child and one closest sibling A A data B C D left child right sibling B C D E F G H I J E F G H I J K L M K L M
Degree-Two Tree 分支度為2的樹 A B A C E B C D F K G D E F G H I J L H M I K L M J Left Child-Right Sibling Tree Binary Tree 二元樹
Tree Representations D D D A A A B B B A A A B C B B C C Left child-right sibling tree Binary tree
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 (右子樹). There is no tree with zero nodes. But there is an empty binary tree. Binary tree distinguishes between the order of the children while in a tree we do not. A A B B Two different binary trees
Binary Tree Examples A A A B C B B D E F G H I n0 = n2 + 1 (see next page) A B C D E Complete binary tree 完整二元樹 Skewed tree 歪斜樹
Properties (特性,性質) of Binary Trees Lemma 5.2 [Maximum number of nodes] The maximum number of nodes on level iof a binary tree is 2i–1, i 1. The maximum number of nodes in a binary tree of depth k is 2k – 1, k 1. Lemma 5.3 [Relation between number of leaf nodes and nodes of degree 2]: For any non-empty binary tree, T, if n0 is the number of leaf nodes and n2 the number of nodes of degree 2, then n0 = n2 + 1. Definition: A full binary tree(完滿二元樹) of depth k is a binary tree of depth k having 2k – 1 nodes, k 0. (perfect binary tree @wiki)
Full Binary Tree v.s. 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 1 2 2 3 3 6 6 4 4 7 7 5 5 12 12 13 13 8 8 9 9 14 14 15 15 10 10 11 11 level 1 2 3 4 complete binary tree 完整二元樹 full binary tree (perfect binary tree) (?)n0 = n2 + 1 (?)2i–1 (?)2k – 1
Array Representation of a Binary Tree Lemma 5.4: If a complete binary tree with n nodes is represented sequentially, then for any node with index i, 1 in, we have: parent(i) is at if i ≠1. If i = 1, i is at the root and has no parent. left_child(i) is at 2i if 2in. If 2i > n, then i has no left child. right_child(i) is at 2i + 1 if 2i + 1 n. If 2i + 1 > n, then i has no right child. Position zero of the array is not used.
Array Representation of Binary Trees A [1] A A [2] B B [3] B C [4] C [5] C [6] D E F G D [7] [8] D H I [9] E [16] E A [1] [2] B C [3] [4] D [5] E [6] F G [7] [8] H complete binary tree 完整二元樹 I [9] skewed tree 歪斜樹
Linked Representation of Binary Trees class Tree; class TreeNode { friendclass Tree; private: TreeNode *leftChild; char data; TreeNode *rightChild; }; class Tree { public: // Tree operations ... private: TreeNode *root; }; data leftChild rightChild leftChild data rightChild
Linked List Representation for the Binary Trees A E H 0 I 0 root root A 0 B 0 C B C 0 D 0 0 0 F 0 0 G 0 D 0 0 0 0 E 0 complete binary tree skewed tree
Tree Traversal 走訪;追蹤 When visiting each node of a tree exactly once, this produces a linear order (線性順序) for the node of a tree. L: left V: visit R: right There are 3 traversals if we adopt the convention that we traverse left before right: LVR (inorder), LRV (postorder), and VLR (preorder). When implementing (實作) the traversal, a recursion (遞迴) is perfect for the task. VRL, RVL, RLV: traversing right before left
Binary Tree with Arithmetic Expression Inorder Traversal: A/B*C*D+E => Infix form 中序 Preorder Traversal: +**/ABCDE => Prefix form 前序 Postorder Traversal: AB/C*D*E+ => Postfix form 後序 + * E * D / C A B 算術、計算
Inorder Traversal template<class T> void Tree <T>::Inorder() {//Driver calls workhorse for traversal of entire tree Inorder(root); } template<class T> void Tree <T>::Inorder (TreeNode <T>*currentNode) {//Workhouse traverses the subtree rooted at currentNode If (currentNode){ Inorder(currentNode->leftChild); Visit(currentNode); Inorder(currentNode->rightChild); } }
Iterative Inorder Traversal void Tree::NonrecInorder() // nonrecursive inorder traversal using a stack { Stack<TreeNode *> s;// declare and initialize stack TreeNode *currentNode = root; while(1){ while(currentNode){// move down LeftChild fields s.Push(currentNode); // add to stack currentNode = currentNode->leftChild; } if(!s.IsEmpty()){ // stack is not empty currentNode =*s.Top(); s.Pop(); // delete from stack cout << currentNode->data << endl; currentNode = currentNode->rightChild; } elsebreak; } }
Level-Order Traversal 階序走訪 All previous mentioned schemes usestacks. A/B*C*D+E; +**/ABCDE; AB/C*D*E+ Level-order traversal uses a queue. Level-order scheme visitsthe root first, then the root’s left child, followed by the root’s right child. All the node at a level are visited before moving down to another level. + * E * D / C A B Level-Order Traversal: +*E*D/CAB
Level-Order Traversal of a Binary Tree void Tree::LevelOrder() // Traverse the binary tree in level order { Queue<TreeNode *> q; TreeNode *currentNode = root; while(currentNode){ cout << currentNode->data << endl; if(currentNode->leftChild) q.Push(currentNode->leftChild); if(currentNode->lightChild) q.Push(currentNode->rightChild); if(q.IsEmpty())return; currentNode =*q.Front(); q.Pop(); } } + * E * D / C A B +*E*D/CAB
Traversal without a Stack Use of parent field to each node. Use of two bits per node to represents binary trees as threaded binary trees.
Some Other Binary Tree Functions With the inorder, postorder, or preorder mechanisms, we can implement all needed binary tree functions. E.g., Copying Binary Trees 複製二元樹 Testing Equality 測試是否相等 Two binary trees are equal if their topologies (拓樸,架構)are the same and the information in corresponding nodes is identical (完全相同的).
The Satisfiability (滿足性) Problem Expression Rules A variable is an expression (邏輯式) If x and y are expressions then are expressions Parentheses (括號) can be used to alter (改變) the normal order (次序、順序) of evaluation (計算), which is not before and before or.
Propositional Formula in a Binary Tree 命題 式 x3 x1 x3 x2 x1 { ttt, ttf, tft, tff, ftt, ftf, fft, fff} Time complexity: O(g2n)
Perform執行Formula Evaluation計算 To evaluate an expression, we can traverse its tree in postorder. To perform evaluation, we assume each node has four fields LeftChild data value RightChild RightChild value data LeftChild
First Version of Satisfiability Algorithm for all2n possible truth value combinations for the n variables { Generate the next combination; Replace the variables by their values; Evaluate the formula by traversing the tree it points to in postorder; if(formula.rootvalue()){cout << combination; return; } } cout <<"no satisfiable combination";
Evaluating a Formula void SatTree::PostOrderEval()// Driver { PostOrderEval(root); } void SatTree::PostOrderEval(SatNode * s)// workhorse { if(s){ PostOrderEval(s->leftChild); PostOrderEval(s->lightChild); switch(s->data){ caseLogicalNot: s->value =!s->rightChild->value;break; caseLogicalAnd: s->value = s->leftChild->value && s->rightChild->value; break; caseLogicalOr: s->value = s->leftChild->value || s->rightChild->value; break; case LogicalTrue: s->value = TRUE;break; case LogicalFalse: s->value = FALSE; } } }
§5.5 Threaded Binary Tree 引線二元樹 Threading Rules A 0 rightChild field at node p is replaced by a pointer to the node that would be visited after p when traversing the tree in inorder. That is, it is replaced by the inorder successor of p. A 0 leftChild link at node p is replaced by a pointer to the node that immediately precedes node p in inorder (i.e., it is replaced by the inorder predecessor of p).
Threaded Tree of Figure 5.10(b) A B C D E F G H I A B C D E F G H I Inorder sequence: H, D, I, B, E, A, F, C, G
Memory Representation of Threaded Tree - D f f f f A A f f B C B f f B f f D E F G t E t t D t t E t H I H t I t t t LeftThread LeftChild RightChild RightThread data TRUE FALSE Empty Binary Tree • t->LeftChild = TRUE => t->LeftChild is a thread • t->LeftChild = FALSE • => t->LeftChild is a pointer to the left child.
Finding the Inorder Successor without Stack A B C D E F G H I Inorder sequence: H, D, I, B, E, A, F, C, G • By using the threads, we can perform an inorder traversalwithout making use of a stack. T* ThreadedInorderIterator::Next() {//Return the inorder successor of currentnode ThreadedNode <T>*temp = currentNode -> rightChild; if(!currentNode->rightThread) while(!temp->leftThread) temp = temp -> leftChild; currentNode = temp; if(currentNode == root)return0; elsereturn¤tNode -> data; }
Insertion of r as a Right Child of sin a Threaded Binary Tree If the right subtree of s is empty s s r r after before
Insertion of r as a Right Child of sin a Threaded Binary Tree (Cont.) r If the right subtree of s is not empty s s r r after before
Program 5.16 Inserting r as the Right Child of s void ThreadedTree::InsertRight(ThreadNode *s, ThreadedNode *r) // Insert r as the right child of s { r->RightChild = s->RightChild; r->RightThread = s->RightThread; r->LeftChild = s; r->LeftThread = TRUE;// LeftChild is a thread r->RightChild = r;// attach r to s r->RightThread = FALSE; if(!r->RightThread){ // returns the inorder successor of r ThreadedNode *temp = InorderSucc(r); temp->LeftChild = r; } }
§5.6 Heaps 堆積 §5.6.1Priority Queues 優先權佇列 In a priority queue, the element to be deleted is the one with highest (or lowest) priority. An element with arbitrary priority can be inserted into the queue according to its priority. A data structure supports the above two operations is called max (min) priority queue.
Priority Queue with Linked List Unorder Linear List Addition complexity: O(1) Deletion complexity: O(n) Chain Addition complexity: O(1) Deletion complexity: O(n) Ordered List Addition complexity: O(n) Deletion complexity: O(1) first CAT BAT EAT FAT GAT HAT 0
§5.6.2 Max (Min) Heap 最大(最小)堆積 Heaps are frequently used to implement priority queues. The complexity is O(log n). Definition: A max (min) 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). 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.
30 9 14 25 3 6 12 7 8 10 6 5 Max Heap Examples 11 10 2 21 83 20 7 4 8 10 6 50 Min Heap Examples
Insertion into a Max Heap 20 20 (a) (b) 2 15 2 10 14 21 (b)(c1)Insert 5 (b)(c2)Insert 21 20 20 15 5 5 15 5 10 2 14 10 2 14
Deletion from a Max Heap template<class Type> void MaxHeap <T>::Pop() {// Delete from the max heap if(IsEmpty())throw "Heap is empty."; heap[1].~T();//delete max element //remove last element from heap T lastE = heap [heapSize--]; int currentNode =1; int child =2; while(child >= leapSize) { if(child < heapSize && heap[child]< heap[child+1]) child++; if(lastE >= heap[child])break; heap[currentNode]= heap[child]; currentNode = child; child *=2; } heap[currentNode]= lastE; }
Deletion from a Max Heap 21 2 (a) (b) 20 15 20 15 10 2 14 10 2 14 2 20 (c) (d) 20 2 15 15 10 10 14 14
Deletion from a Max Heap (Cont.) 20 10 (e) (f) 2 15 2 15 10 14 10 14 10 15 (g) (i) 2 2 15 14 14 10
§5.7 Binary Search Tree二元搜尋樹 Definition: A binary search tree is a binary tree. It may be empty. If it is not empty then it satisfies the following properties: Every element has a key and no two elements have the same key (i.e., the keys are distinct) The keys (if any) in the left subtree are smaller than the key in the root. The keys (if any) in the right subtree are larger than the key in the root. The left and right subtrees are also binary search trees.
Binary Trees 60 30 20 70 5 40 15 25 80 65 14 10 22 2 Binary search trees Not binary search tree