Presentation is loading. Please wait.

Presentation is loading. Please wait.

Tirgul 12 Trees 1.

Similar presentations


Presentation on theme: "Tirgul 12 Trees 1."— Presentation transcript:

1 Tirgul 12 Trees 1

2 Trees Definitions: A,B, C… ,I: nodes. (AB), (AC), (HI)…: edges
A is the root of the tree D, E, F, G, I: leaves. A,B,C,H: internal nodes B, C, H are the roots of the subtrees

3 Binary trees Each node has at most 2 children

4 BinaryTreeNode public class TreeNode{ private int number;
private TreeNode leftSon, rightSon; public TreeNode (int number){ number = number; leftSon = null; rightSon = null; } public int getNumber() { return number; } public TreeNode getLeftSon(){ return leftSon; } public TreeNode getRightSon(){ return rightSon; }

5 public static boolean isLeaf(TreeNode t) }
return ( t.getLeftSon()==null && t.getRightSon()==null ); {

6 Count leaves public static int numOfLeaves(TreeNode root) }
if(root==null) return 0; if( root.isLeaf() ) return 1; return numOfLeaves(root.getLeftSon()) numOfLeaves(root.getRightSon() ); {

7 Some numbers A full binary tree has n leaves. How many levels are there in the tree (what is the hight)? log (n) + 1 A binary tree has k levels, what is the maximal number of leaves the tree has? 2^(k-1) And what is the maximal number of nodes in a binary tree of k levels? 2^(k)-1

8 Find minimal value in a binary tree
public static int minNode(TreeNode t) { int number = t.getNumber(); if(isLeaf(t)) { return number; } TreeNode right = t.getRightSon(); TreeNode left = t.getLeftSon(); if(right == null) { return Math.min(number, minNode(left)); if(left == null) { return Math.min(number, minNode(right)); return Math.min(number, Math.min(minNode(left),minNode(right)) ); What is the runtime complexity? And space complexity?

9 Family tree Me Mom Dad Mom’s mom Mom’s dad Dad’s mom Dad’s dad

10 Family tree class FamilyPerson { FamilyPerson mother; FamilyPerson father; String name; public FamilyPerson(…) {…} } This is the node of the tree. Each node has two “children” nodes – its parents

11 Order of traversal on trees
Say we want to print all nodes in a tree. In what order? We can take a depth-first, or breadth-first strategy. Breadth-first search (BFS): Visit all nodes in the i’th level of the tree, before visiting all nodes in the (i+1) level. Depth-first search (DFS): One of pre-order, post-order, or in-order.

12 Family tree – BFS traversal
public static BFS(FamilyPerson root) { Queue<FamilyPerson> q = new Queue();//some class that implements queue q.push(root); while (!q.empty()) { FamilyPerson node = q.pop(); if (node == null) { continue; } System.out.println(node.name); q.push(node.mother); q.push(node.father);

13 Family tree – BFS traversal
Me Me Mom Dad Mom’s mom Mom Dad Mom’s dad Dad’s mom Dad’s dad Mom’s mom Mom’s dad Dad’s mom Dad’s dad

14 Family tree – DFS (pre-order)
public static void preOrder(FamilyPerson root) { if (root == null) { return; } System.out.println(root.name); preOrder(root.mother); preOrder(root.father);

15 Family tree – DFS (pre-order)
Me Me Mom Mom’s mom Mom’s dad Mom Dad Dad Dad’s mom Dad’s dad Mom’s mom Mom’s dad Dad’s mom Dad’s dad

16 Family tree – DFS (post-order)
public static void postOrder(FamilyPerson root) { if (root == null) { return; } postOrder(root.mother); postOrder(root.father); System.out.println(root.name);

17 Family tree – DFS (post-order)
Mom’s mom Me Mom’s dad Mom Dad’s mom Mom Dad Dad’s dad Dad Me Mom’s mom Mom’s dad Dad’s mom Dad’s dad

18 Family tree – DFS (in-order)
public static void inOrder(FamilyPerson root) { if (root == null) { return; } inOrder(root.mother); System.out.println(root.name); inOrder(root.father);

19 Family tree – DFS (in-order)
Mom’s mom Me Mom Mom’s dad Me Mom Dad Dad’s mom Dad Dad’s dad Mom’s mom Mom’s dad Dad’s mom Dad’s dad

20 Binary search tree Let’s say you keep a phone book with many details on the people. You want to add people to the book (quickly) and to search a person in the book quickly according to their name.

21 public Person { String name; int age; ...// more fields, telephone number... } public PhoneBook { private static Node { private Person person; private Node rightChild; private Node leftChild; ...

22 public PhoneBook { ... private Node head = null; public void add(Person p) { // How would you implement it? // What is the runtime complexity? } public Person search(String name) {

23 שאלה ממועד ב' 2011/12 נתונה המחלקה הבאה לייצוג עץ בינארי: public class Tree { private int data; private int size; // number of nodes in this subtree private Tree left, right; private Tree parent; // the parent of this subtree public Tree(int data) { this.data = data; size = 1; left = right = parent = null; } void balancedInsert(int value) { } void mirror() { } int countNodesAtLevel(int level) { } א. (13 נקודות) עץ בינארי מאוזן הוא עץ שבו לכל צומת הגדלים של שני תתי העצים שלו (מספר הצמתים שכל אחד מהם מכיל) נבדלים זה מזה ב-1 לכל היותר. עליכם לממש (ללא שימוש ברקורסיה) את השיטה balancedInsert. שיטה זו מוסיפה ערך חדש לעץ בינארי תוך שמירה על היותו מאוזן ועדכון כנדרש של כל שדות מבנה הנתונים. בפרט, אם מתחילים מעץ מאוזן ומוסיפים אליו מספר כלשהו של ערכים באמצעות שיטה זו, לאחר סדרת ההוספות הנ"ל עדיין על העץ להיות מאוזן. שימו לב: אין דרישה שהעץ יהיה עץ חיפוש, הדרישות הן אך ורק לגבי איזון. ב. (3 נקודות) מהי הסיבוכיות של השיטה שמימשתם (הביעו באמצעות n, כאשר n הוא מספר הערכים בעץ).

24 void balancedInsert(int value) {
Tree current = this; while (current.left != null && current.right != null) current = (current.left.size <= current.right.size) ? current.left : current.right; Tree node = new Tree(value); node.parent = current; if (current.left == null) current.left = node; else current.right = node; current.size++; while (current.parent != null) { current = current.parent; }

25 if (left == null && right == null) return; Tree node = left;
ג. (7 נקודות) ממשו את השיטה mirror אשר משנה את העץ לשיקוף ראי של עצמו (כלומר עבור כל צומת בנו הימני הופך להיות בנו השמאלי ובנו השמאלי הופך להיות בנו הימני). מותר להשתמש ברקורסיה. מומלץ להתחיל בכך שתציירו דוגמה לא טריויאלית (עץ המכיל 5 ערכים לפחות והשיקוף שלו). void mirror() { if (left == null && right == null) return; Tree node = left; left = right; right = node; if (left != null) left.mirror(); if (right != null) right.mirror(); }

26 ד. (7 נקודות) ממשו את השיטה countNodesAtLevel אשר מחזירה את מספר הצמתים בעץ בעומק בדיוק level מן הצומת שעליו נקראה השיטה. כאן לא ניתן להניח כי העץ מאוזן. מותר להשתמש ברקורסיה. לצורך העניין, נגדיר שכל צומת נמצא בעומק 0 מעצמו. int countNodesAtLevel(int level) { if (level == 0) return 1; int leftCount = (left == null) ? 0 : left.countLevel(level-1); int rightCount = (right == null) ? 0 : right.countLevel(level-1); return leftCount + rightCount; } ה. (4 נקודות) חשבו את סיבוכיות כל אחת מהשיטות אשר כתבתם בסעיף ג' ו-ד'.


Download ppt "Tirgul 12 Trees 1."

Similar presentations


Ads by Google