1 / 78

Trees --Part I

Trees --Part I. Lai Ah Fur. definition. A tree can be defined recursively as the following: An empty structure is an empty tree If t 1 ,…,t k are disjoint trees, then the structure whose root has its children the roots of t 1 ,…,t k is also a tree.

aliza
Download Presentation

Trees --Part I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Trees--Part I Lai Ah Fur

  2. definition • A tree can be defined recursively as the following: • An empty structure is an empty tree • If t1,…,tk are disjoint trees, then the structure whose root has its children the roots of t1,…,tk is also a tree. • Only structures generated by previous two rules are trees. • A tree is a finite set of one or more node such that: • There is a specially node designated node called the root. • The remaining nodes are partitioned into n>=0 disjoint sets t1,…,tn,where each of the sets is a tree. We call t1,…,tn the subtrees of the root.

  3. Organize a hierarchical representation of objects. • FOREST: after removing the root, all the subtrees become one of set of the forest • Types: binary tree, binary search tree(BST), AVL tree, Red-Black tree,2-3 tree, 2-3-4 tree, B-tree

  4. Terms:path,length,level,height • Each node has to reachable from the root through a unique sequence of arcs, called a path. • The number of arcs in a path is called the length of the path. • The level of a node is the the length of the path from the root to the node plus 1, which is the number of nodes in the path. • The height (depth) of a nonempty tree is the maximumlevel of a node in the tree. • The empty tree is a legitimate tree of height 0. • A single node is a tree of height 1 ( a node is both the root and a leaf).

  5. A LEVEL=1 D C B I E H F G L J K M N O LEVEL=5 Terms (2) • DEGREE • PARENT/CHILD/SIBLING • ANCESTOR/DESCENDANT • TERMINAL NODE (LEAF)/ NON-TERMINAL NODE (internal node) • subtree

  6. Compare the linked list and tree? • Your exercise?

  7. Binary tree • A binary tree is a tree whose node have two children(possible empty), and each children is designated as either a left child or a right child. • A complete binary tree: all nonterminal nodes have both their children, and all leaves are at the same level. There are at most 2i nodes at level i+1. • A full binary tree: The tree which has the height k contains 2k-1 nodes.

  8. A C B F D E Representation of a binary tree • List: (A(B(D()())(E()()))(C()(F()())) • Array • link

  9. A C B F D E I G H J EXCERSIZE • LIST? • ARRAY? (RULE?)

  10. Binary search tree • Also called orderedbinary tree • For each node n of the tree, all values in its left subtree are less than value v stored in n, and all values stored in the right subtree are greater thanv.

  11. Binary-search-tree (BST) BST property: Let x be a node in a BST. • If y is a node in the left subtree of x, then key[y] < key[x]. • If y is a node in the right subtree of x, then key[x] < key[y]. Tree construction: Worst case: O(n2); average case: O(nlgn), where n is the # of nodes Operations Search, Minimum, Maximum, Predecessor, Successor, Insert, Delete can be performed in O(h) time, where h is the height of the tree. ˙Worst case: h = -(n); balanced BST: h = -(lgn). ˙Can we guarantee h = -(lgn)? Balance search trees!!

  12. 二元樹的特性 (1)二元樹中,階度(level)為i的最大節數是2i-1,i≧0 證明:利用歸納法證明 步驟1:樹根是唯一階度為l的節點,因此階度i=l時最大的節點為2i-l=2l-l=l 步驟2:對所有j,l≦j<I,階度j上最大的節數為2j-l。 步驟3:由步驟2知,i-l階度上最大的節數為2i-2,而二元樹中每一節的分支度均≦2,因此階度i上最大的節數等於2乘以階度i-l上的最大節數,也就是2i-l。

  13. (2)若二元樹的深度為k,則此二元樹最多的節數目為2k-l。(2)若二元樹的深度為k,則此二元樹最多的節數目為2k-l。 • 證明:深度為k的二元樹,其最多的節數目等於階度l到階度k中各階度最大節數的和,亦即 2i-1=20+21+……+2k-2+2k-1 =(2k-1)/(2-1)=2k-1

  14. (3)任何一個非空二元樹T,若終端節點總數為n0,且分支度等於2的節點數是n2,則n0=n2+1。(3)任何一個非空二元樹T,若終端節點總數為n0,且分支度等於2的節點數是n2,則n0=n2+1。 證明: • 設n1是分支度(degree)等於1的節點數,n是總節數,因為T中有節點的分支度都≦2,所以 n=n0+n1+n2--------------------------------------(1) • 二元樹中,除了樹根以外,每一個節點都有一個分支(branch)指向它,令B是分支數。 因此B=n-1---------------------------------------(2) 而所有的分支(分支總數)都是由分支度等於1或2的節點指, 故B=n1+2n2--------------------------------------(3) • 由(2)與(3)得 n-1=n1+2n2 • 代入(1)式得 n0+n1+n2-1=n1+2n2 移項理可得 n0=n2+1

  15. BST node public class IntBSTNode { protected int key; protected IntBSTNode left, right; public IntBSTNode() { left = right = null; } public IntBSTNode(int el) { this(el,null,null); } public IntBSTNode(int el, IntBSTNode lt, IntBSTNode rt) { key = el; left = lt; right = rt; } public void visit() { System.out.print(key + " "); } }

  16. Tree traversal • Tree traversal is the process of visiting each node in the tree exactly one time. • Linearizing a tree • For a tree with n nodes, there are n! different traversals. Most of them are useless. • Breadth-first traversal • Depth-first traversal

  17. A C B F D E I G H J Breadth-first traversal • Visit each node starting from the lowest (or highest) level and move down (or up) level by level, visit nodes on each level from left to right (or from right to left). • Four possibilities • Result:A,B,C,D,E,F,G,H,I,J • Implementation : • needs a queue.

  18. Top-down, left to right, Breadth-first traversal public void breadthFirst() { IntBSTNode p = root; Queue queue = new Queue(); if (p != null) { queue.enqueue(p); while (!queue.isEmpty()) { p = (IntBSTNode) queue.dequeue(); p.visit(); if (p.left != null) queue.enqueue(p.left); if (p.right != null) queue.enqueue(p.right); } } }

  19. Depth-first traversal • Three tasks: • V:visiting a node • L:traversing the left subtree • R:traversing the right subtree • Six possible ordered depth-first traversals: • VLR VRL LVR RVL LRV RLV • Preorder traversal: VLR • Inorder traversal: LVR • Postorder traversal: LRV

  20. A C B F D E I G H J EXAMPLE • PREORDER:VLR • A,B,D,G,E,H,C,F,I,J • INORDER: LVR • GDBEHACFJI • POSTORDER: LRV • GDHEBJIFCA

  21. A C B F D E J G H I K L L N EXCERCISE • PREORDER:VLR • ? • INORDER: LVR • ? • POSTORDER: LRV • ?

  22. Preorder (RECURSIVE) protected void preorder(IntBSTNode p) { if (p != null) { p.visit(); preorder(p.left); preorder(p.right); } }

  23. Preorder (ITERATIVE) public void iterativePreorder() { IntBSTNode p = root; Stack travStack = new Stack(); if (p != null) { travStack.push(p); while (!travStack.isEmpty()) { p = (IntBSTNode) travStack.pop(); p.visit(); if (p.right != null) travStack.push(p.right); if (p.left != null) travStack.push(p.left); // left child pushed after right ,to be on the top of the Stack; } } }

  24. Inorder (RECURSIVE) protected void inorder(IntBSTNode p) { if (p != null) { inorder(p.left); p.visit(); inorder(p.right); } }

  25. Inorder(iterative) public void iterativeInorder() { IntBSTNode p = root; Stack travStack = new Stack(); while (p != null) { while(p != null) { // stack the right child (if any) if (p.right != null) // and the node itself when going travStack.push(p.right); // to the left; travStack.push(p); p = p.left; } p = (IntBSTNode) travStack.pop(); // pop a node with no left child while (!travStack.isEmpty() && p.right == null) { // visit it and all p.visit(); // nodes with no right child; p = (IntBSTNode) travStack.pop(); } p.visit(); // visit also the first node with a right child (if any); if (!travStack.isEmpty()) p = (IntBSTNode) travStack.pop(); else p = null; // is over} }

  26. Postorder (RECURSIVE) protected void postorder(IntBSTNode p) { if (p != null) { postorder(p.left); postorder(p.right); p.visit(); } }

  27. Postorder(iterative-1) public void iterativePostorder() { IntBSTNode p = root; Stack travStack = new Stack(); //trace用堆疊 output = new Stack(); //結果堆疊 if (p != null) { // left-to-right postorder = right-to-left preorder LRV travStack.push(p); while (!travStack.isEmpty()) { p = (IntBSTNode) travStack.pop(); output.push(p); if (p.left != null) travStack.push(p.left); if (p.right != null) travStack.push(p.right); } //while while (!output.isEmpty()) { p = (IntBSTNode) output.pop(); p.visit(); } } }

  28. P q Both has visited Postorder(iterative-2) public void iterativePostorder() { BSTNode p = root,q=root; Stack travStack = new Stack(); while ((p != null) { for(;p.left!=null ;p=p.left) travStack.push(p); while ((p != null)&& (p.right==null ||p.right==q)) { p.visit(); q=p; //q has been visited If (travStack.isEmpty()) return ; p= (BSTNode) travStack.pop(); }//while travStack.push(p); p=p.right; }//while }

  29. search protected IntBSTNode Search(IntBSTNode p, int el) { while (p != null) if (el == p.key) return p; else if (el < p.key) p = p.left; else p = p.right; return null; }

  30. 15 NULL (A)insert 15 INSERT (BST) 20 4 15 15 4 (c) insert 20 (B)insert 4 15 19 17 15 15 4 20 4 20 17 4 20 17 19 (D)insert 17 (E)insert 19 (F)

  31. CREATE a BST USING INSERT • Given the following integer sequence, please create the BST: 50,67,23,45,87,99,34,12,44,90,100,10,11,35,111

  32. insert public void insert(int el) { IntBSTNode p = root, prev = null; while (p != null) { // find a place for inserting new node; prev = p; if (p.key < el) p = p.right; else p = p.left; } if (root == null) // tree is empty; root = new IntBSTNode(el); else if (prev.key < el) prev.right = new IntBSTNode(el); else prev.left = new IntBSTNode(el); }

  33. Delete a node • Delete by merging • Delete by copying Delete 16 Free the space Delete 20 Free the space

  34. Delete by merging • Make one tree out of the two subtrees of the node, then attach it to the node’s parent • How to merge these subtrees? • Find in the left subtree the node with the greatest value and make it a parent of the right subtree • Find in the right subtree the node with the lowest value and make it a parent of the left subtree • Drawback: increase the height of the tree (It is certainly far from perfect!)

  35. Delete node Delete by merging Root Root node left node left node right node node left node left node right Rightmost node of the left subtree node right

  36. Delete by merging (example) Delete 15 Delete 15

  37. Details of deleting by merging

  38. Delete by copying • Proposed by Hilbard & Knuth • If the node has 2 children, it can be replaced with its immediate predecessor (or successor) • This algorithm doesn’t increase the height of the tree, but it may cause the unbalanced problem.

  39. A C M A F C D E B F J D E G H I K L J P N G H I K L M N Delete by copying (example) P Other? Delete B

  40. Details of deleting by copying

  41. Case 1 prev prev node node p p Case 2 prev node p Deleting node (1) if (node.right == null) //node has no right child; node = node.left; else if (node.left == null) //no left child for node; node = node.right; if (p == root) root = node; else if (prev.left == p) prev.left = node; else prev.right = node;

  42. prev node p previous tmp prev previous node p tmp Deleting node (2) if (node.right != null &&node.right != null) {// node has both children; BSTNode tmp = node.left; BSTNode previous = node; // 1. while (tmp.right != null) { // 2. find the rightmostposition in the left subtree of node; previous = tmp; // tmp = tmp.right; //} node.key = tmp.key; // 3. overwrite the reference // of the key being deleted; if (previous = = node) // if node's left child's right subtree is null previous.left = tmp.left;; else previous.right = tmp.left; } …….

  43. 20 25 16 30 10 17 40 5 15 18 3 7 13 35 exercise • Delete 16,請用三種做法 • insert 28 • Design the class of the node of this BST (java)

  44. 4 1 7 4 4 4 0 2 5 8 1 1 3 6 9 0 2 Balancing a tree • Stream of data: 5,1,9,8,7,0,2,3,4,6 • Array of sorted data:0,1,2,3,4,5,6,7,8,9 public void balance(BaseObject data[], int first, int last) { if (first <= last) { int middle = (first + last)/2; insert(data[middle]); balance(data,first,middle-1); balance(data,middle+1,last); } } Drawback: All data must be put in an array before the tree can be created.

  45. 二元樹的計數(Counting Binary Tree) • n個節可排成多少個不同的二元樹? (1)n=0或者n=1,祇有一種二元樹 (2)n=2時,存在兩種不同的二元樹。 (3)n=3時,存在五種不同的二元樹。

  46. 二元樹的計數 • n個節點所能排成不同二元樹的個數可以列公式求出:

  47. 中序順序及前序順序決定一個二元樹 例:有一個前序順序為:ABCDEFGHI 中序順序為:BCAEDGHFI 則其相對應的二元樹為何? • 解:前序追蹤的第一個字元A一定是樹根,再從中序追蹤知在A之前的節點BC是左子樹,在A之後的節點EDGHFI是右子樹,由此我們可以大略的建立出其相對應的二元樹形狀。 • 再由前序追蹤的第二個字元B知其為樹根,從中序追蹤知B的左子樹是空的,右子樹是C,因此其進一步結果如下: • 同理類推,整個二元樹如下所示:

  48. 一對中序順序(inorder sequence)及前序順序(preorder sequence)可唯一決定一個二元樹。 • 一對中序順序(inorder sequence)及後序順序(postorder sequence)亦可唯一決定一個二元樹。  • 一對前序順序(preorder sequence)及後序順序(postorder sequence)無法決定唯一一個二元樹

  49. a b d e f g exercise • 有一個前序順序為:ABDEFG 中序順序為:BAEDGF 則其相對應的二元樹為何?

More Related