1 / 37

Tirgul 13: Trees

Tirgul 13: Trees. הגדרות. עץ – מודל מופשט של מבנה היררכי. עץ מורכב מאוסף של צמתים (קודקודים) עם יחס אבא-בן. שורש בעץ – צומת ללא אבא. בכל עץ יש בדיוק שורש אחד. לכל הצמתים פרט לשורש יש בדיוק אב אחד. הגדרות. X.

qamar
Télécharger la présentation

Tirgul 13: Trees

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. Tirgul 13:Trees

  2. הגדרות • עץ – מודל מופשט של מבנה היררכי. עץ מורכב מאוסף של צמתים (קודקודים) עם יחס אבא-בן. • שורש בעץ – צומת ללא אבא. בכל עץ יש בדיוק שורש אחד. לכל הצמתים פרט לשורש יש בדיוק אב אחד.

  3. הגדרות X • צומת X הינו אב קדמון של צומת Y, ו Y הנו צאצא של X אם המסלול מהשורש אל Y עובר דרך X. • צומת X הנו האבא של W, ו W הנו בן של X אם X הנו אב קדמון של W ויש ביניהם צלע W Y

  4. הגדרות • עלה – צומת אשר אין לו בנים. • עומקשל צומת בעץ= מרחק הצומת מהשורש.

  5. הגדרות • גובהשל העץ – עומק מקסימאלי של צומת בעץ (וגובה של עץ ריק הוא -1). • עץ בינארי - עץ אשר בו מספר הבנים של כל צומת אינו עולה על 2.

  6. הגדרות עץ חיפוש בינארי עץ בינארי אשר בו עבור כל צומת, הערכים של כל האיברים בתת העץ השמאלי שלו קטנים (או שווים) ממנו, וכל האיברים בתת העץ הימני שלו גדולים ממנו. 7 3 10 6 1 14 4 7 13

  7. 1 6 3 5 8 2 9 שלוש שיטות לסריקת עץ pre-order, in-order ,post-order. בביצוע הסריקות בעץ הנתון יתקבל סדר האיברים הבא: • תחילי (pre-order): • תוכי (in-order): • סופי (post-order): מה הייתה התוצאה אם העץ היה binary search tree? 1,6,8,5,2,9,3 8,6,2,5,9,1,3 8,2,9,5,6,3,1

  8. הגדרות: עוקב וקודם העוקב לצומת x: הצומת בעל מפתח הקטן ביותר הגדול מערך שלx הקודם לצומתx: הוא הצומת בעל מפתח הגדול ביותר הקטן מערך שלx דוגמה: הקודם של W הוא העוקב של W הוא הקודם של C הוא העוקב של C הוא ב- BST, לפי סריקת inOrder: R Y B E

  9. דוגמא

  10. מימוש: עץ

  11. BinaryTree publicclassBinaryTree { protectedBinaryNoderoot; publicBinaryTree() { root = null; } // BinaryTree publicbooleanisEmpty() { returnroot == null; } // isEmpty publicvoid insert(Object toAdd) { if (isEmpty()) root = newBinaryNode(toAdd); else root.insert(toAdd); } // insert public String inOrder() { if (isEmpty()) return""; else returnroot.inOrder(); } // inOrder public String preOrder() { if (isEmpty()) return""; elsereturnroot.preOrder(); } // preOrder public String postOrder() { if (isEmpty()) return""; else returnroot.postOrder(); } // postOrder }

  12. BinaryNode publicvoid insert(Object toAdd) { double select = Math.random(); if (select > 0.5) { if (left == null) left = newBinaryNode(toAdd); else left.insert(toAdd); } else { if (right == null) right = newBinaryNode(toAdd); else right.insert(toAdd); } } // insert publicclassBinaryNode { protected Object data; protectedBinaryNodeleft; protectedBinaryNoderight; publicBinaryNode(Object data) { this.data = data; left = null; right = null; } // BinaryNode … }

  13. BinaryNode public String preOrder() { String res = ""; if (data == null) res = res + " <null> "; else res = res + " " + data.toString() + " "; if (left != null) res = res + left.preOrder(); if (right != null) res = res + right.preOrder(); return res; } // preOrder public String inOrder() { String res = ""; if (left != null) res = res + left.inOrder(); if (data == null) res = res + " <null> "; else res = res + " " + data.toString() + " "; if (right != null) res = res + right.inOrder(); return res; } // inOrder

  14. BinaryNode public String postOrder() { String res = ""; if (left != null) res = res + left.postOrder(); if (right != null) res = res + right.postOrder(); if (data == null) res = res + " <null> "; else res = res + " " + data.toString() + " "; return res; } // postOrder

  15. דוגמה לשיטות של עצים: חישוב גובה בעץ בינארי כללי במחלקה BinaryNode: publicint height() { int resLeft = -1; int resRight = -1; if (left != null) { resLeft = left.height(); } if (right != null) { resRight = right.height(); } return Math.max(resLeft, resRight) + 1; } // height במחלקה BinaryTree: publicint height() { if (isEmpty()) return -1; else returnroot.height(); } // height

  16. מימוש:עץחיפוש בינארי -BST BinaryTree BinaryNode הורשה BST BSN

  17. BST import java.util.Comparator; publicclass BST extends BinaryTree { private Comparator comp; public BST(Comparator comp) { super(); this.comp = comp; } // BST … // (override insert only) } // class BST publicclass BSN extends BinaryNode { private Comparator comp; public BSN(Object data, Comparator comp) { super(data); this.comp = comp; } // BSN … // (override insert, remove, etc.) } // class BSN

  18. Step 1 Step 2 Step 3 Step 4 Step 5 Step 6 Step 7 importjava.util.Comparator; publicclass Main { publicstaticvoid main(String[] args) { Comparator comp = newIntegerComparator(); BST tree1 = new BST(comp); tree1.insert(new Integer(50)); // Step 1 tree1.insert(new Integer(60)); // Step 2 tree1.insert(new Integer(40)); // Step 3 tree1.insert(new Integer(30)); // Step 4 tree1.insert(new Integer(20)); // Step 5 tree1.insert(new Integer(45)); // Step 6 tree1.insert(new Integer(65)); // Step 7 System.out.println("InOrder: " + tree1.inOrder()); System.out.println("PreOrder: " + tree1.preOrder()); System.out.println("PostOrder: " + tree1.postOrder()); System.out.println("Find Minimum: " + tree1.findMin()); System.out.println("Height: " + tree1.height()); } } 50 60 40 30 20 45 65

  19. IntegerComparator publicclassIntegerComparatorimplements Comparator { publicint compare(Object o1, Object o2) { if (((Integer)o1).intValue() > ((Integer)o2).intValue()) return 1; elseif (((Integer)o1).intValue() == ((Integer)o2).intValue()) return 0; else return -1; } }

  20. CharacterComparator publicclassCharacterComparatorimplements Comparator { publicint compare(Object o1, Object o2) { if (((Character)o1).charValue() > ((Character)o2).charValue()) return 1; elseif (((Character)o1).charValue() == ((Character)o2).charValue()) return 0; else return -1; } }

  21. F B H A D K BST Insert: Example • Example: Insert C C

  22. הכנסה איבר חדש לעץ • במחלקה BST: • publicvoid insert(Object toAdd) • { • if (isEmpty()) { • root = new BSN(toAdd, this.comp); • } • else { • root.insert(toAdd); • } • } // insert במחלקה BSN: publicvoid insert(Object toAdd) { if (comp.compare(toAdd, this.data) < 0) { if (left == null) left = new BSN(toAdd,this.comp); else left.insert(toAdd); } if (comp.compare(toAdd, this.data) > 0) { if (right == null) right = new BSN(toAdd,this.comp); else right.insert(toAdd); } } // insert

  23. מציאת קודקוד בעל מפתח מינימאליבעץ חיפוש בינארי. במחלקה BST: public Object findMin() { if (isEmpty()) { returnnull; // Exceptions are needed... } return ((BSN)root).findMin(); } // findMin במחלקה BSN: public Object findMin() { BinaryNode t=this; while( t.left != null ) t = t.left; return t.data; } // findMin מה היינו צריכים לעשות אם העץ לא היה BST?

  24. דוגמא ממבחן

  25. עץ בינארי מלא ( FULL )עץ בינארי מלא עץ בינארי אשר בו לכל צומת פנימי יש (בדיוק) שני בנים.

  26. עץ בינארי מושלם ( PERFECT )עץ בינארי מושלם עץ בינארי מלא שבו לכל העלים יש אותו עומק.

  27. לכל הקדקודים שלו עד שכבה h-2 יש בדיוק 2 בנים כל הקדקודים ברמה ה h מרוכזים לשמאל עץ בינארי שגובהו hומתקיים: עץ בינארי שלם ( COMPLETE )עץ בינארי שלם

  28. עץ בינארי מושלם בדיקה האם עץ בינארי הוא עץ בינארי מושלם במחלקה BST: publicboolean isPerfect() { return ((BSN)root).isPerfect(); } במחלקה BSN: publicboolean isPerfect() { int h = height(); //class method if (h==0) returntrue; if (h==1) return (!(left==null) && !(right==null)); return (!(left==null) && (left.height() == h - 1) && ((BSN)left).isPerfect() && !(right==null) &&(right.height() == h - 1) && ((BSN)right).isPerfect()); }

  29. ראינו את ההגדרות הבאות:עץ בינארי שלם עץ מושלם (perfect)- עץ בינארי מלא שבו לכל העלים אותו עומק עץ בינארי שלם (complete)עץ בינארי שגובהו h ומתקיים לכל הקדקודים שלו עד שכבה h-2 יש בדיוק 2 בנים כל הקדקודים ברמה ה h מרוכזים לשמאל בדיקה האם עץ בינארי הוא "שלם" עץ בינארי שלם

  30. הוא ריק או הבן השמאלי שלו הוא שורש של עץ שלם בגובה h-1 והבן הימני שלו הוא שורש של עץ מושלם בגובה h-2 או הבן השמאלי שלו הוא שורש של עץ מושלם בגובה h-1 והבן הימני שלו הוא שורש של עץ שלם בגובה h-1 עץ בינארי בגובה h הוא שלם אם ורק אם: בהגדרה רקורסיבית

  31. עץ בינארי שלם אנחנו נבדוק כמה מקרי קצה כי אם גובה העץ הוא 0 או 1 נקבל שדרוש לבדוק אם גובה תת העץ הוא 0 או –1 במחלקה BST: publicboolean isComplete() { return ((BSN)root).isComplete(); } במחלקה BSN: publicboolean isComplete() { int h = height(); //class method if (h==0) returntrue; if (h==1) return (!(left==null)); //the height is 2 and up: boolean has2Sons = (!(left==null) && !(right==null)); boolean case1=false, case2=false; if (has2Sons) { int leftH = left.height(); int rightH = right.height(); case1 = (((leftH == h-1) && ((BSN)left).isComplete()) && (rightH == h-2) && ((BSN)right).isPerfect()); case2 = (((leftH == h-1) && ((BSN)left).isPerfect ()) && (rightH == h-1) && ((BSN)right).isComplete()); } return case1 || case2; }

  32. The End!

  33. 8 3 7 1 2 6 מבחן 2006 סמסטר ב' מועד ב' שאלה 1 • סעיף א ערימה (heap) הינה עץ בינארי ובו המפתח בכל קודקוד גדול (כפי שמוגדר על ידי הממשק Comparable) מהמפתחות בילדיו. דוגמא – העץ להלן מהווה ערימה חוקית אך אם נוסיף לקודקוד בעל המפתח 7 ילד שמאלי עם מפתח 9 נקבל עץ שאינו מהווה ערימה חוקית • בכל הסעיפים בשאלה זו ניתן להניח כי אין בעץ מפתחות בעלי ערך null. • המחלקות Heap ו- HeapNode זהות למחלקות BinaryTree ו-BinaryNode כפי שנלמדו בכיתה ומכילות בנאים (constructors) ושיטות גישה (accessors) בהן ניתן להשתמש מבלי לממשן.

  34. 8 3 7 1 2 6 הוסיפו את השיטה getKeysInRange למחלקות Heap ו-HeapNode השיטה מחזירה רשימה משורשרת המכילה את כל המפתחות בתחום הסגור [cFirst, cLast]. • לדוגמא – הקריאה getKeysInRange( new Integer(3) , new Integer(8)) על הערימה למעלה תחזיר רשימה המכילה את המפתחות 8,3,,67 (לא בהכרח בסדר זה).

  35. public class Heap{ private HeapNode mRoot; public LinkedList getKeysInRange( Comparable cFirst, Comparable cLast ){ // Complete here } } public class HeapNode{ private Comparable mKey; private HeapNode mLeft, mRight; public void getKeysInRange( Comparable cFirst, Comparable cLast, LinkedList lKeys ){ // Complete here } }

  36. In Heap class: public LinkedList getKeysInRange( Comparable cFirst, Comparable cLast ) { LinkedList lKeys = new LinkedList(); if( mRoot != null ) mRoot.getKeysInRange(cFirst,cLast,lKeys); return lKeys; }

  37. In HeapNode class: public void getKeysInRange( Comparable cFirst, Comparable cLast, LinkedList lKeys ) { if( mData.compareTo( cFirst ) >= 0 ){ if( mData.compareTo( cLast ) <= 0 && mData.compareTo( cFirst ) >= 0 ) lKeys.add(mData ); if( mLeft != null ) mLeft.getKeysInRange(cFirst,cLast, lKeys); if( mRight != null ) mRight.getKeysInRange(cFirst,cLast, lKeys); } }

More Related