Tirgul 12 Trees 1.

Slides:



Advertisements
Similar presentations
ממיבחניםC שאלות ++.
Advertisements

1 AVL Trees. 2 AVL Tree AVL trees are balanced. An AVL Tree is a binary search tree such that for every internal node v of T, the heights of the children.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary trees Reading: L&C 9.1 – 9.7.
1 Data Structures, CS, TAU, Splay Tree Splay Tree  מימוש של עץ חיפוש בינארי  מטרה לדאוג ל- Amortized Time  פעולה בודדת יכולה לקחת O(N)  אבל כל רצף.
Data Structures, CS, TAU, Splay Tree 1 Splay Tree - עץ חיפוש בינארי - מטרה לדאוג ל - Amortized Time - פעולה בודדת יכולה לקחת O(N) - אבל כל רצף M פעולות.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
Binary Tree Properties & Representation. Minimum Number Of Nodes Minimum number of nodes in a binary tree whose height is h. At least one node at each.
1 General Trees & Binary Trees CSC Trees Previous data structures (e.g. lists, stacks, queues) have a linear structure. Linear structures represent.
CHAPTER 12 Trees. 2 Tree Definition A tree is a non-linear structure, consisting of nodes and links Links: The links are represented by ordered pairs.
עצים בינאריים - תזכורת דרגת צומת שורש עלה צומת פנימי מרחק בין 2 צמתים
Binary and Other Trees CSE, POSTECH. 2 2 Linear Lists and Trees Linear lists are useful for serially ordered data – (e 1,e 2,e 3,…,e n ) – Days of week.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Introduction to trees.
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
1 Chapter 25 Trees Iterators Heaps Priority Queues.
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 7.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
COSC 1030 Lecture 9 Binary Trees. Topics Basic Concept and Terminology Applications of Binary Tree Complete Tree Representation Traversing Binary Trees.
Tree Traversal.
Trees Isaac Sheff. Nodes Building blocks of trees “Parent” node may have “Child” nodes Can be both parent and child Can’t be its own ancestor Can’t have.
1 Storing Hierarchical Information Lists, Stacks, and Queues represent linear sequences Data often contain hierarchical relationships that cannot be expressed.
Rudiments of Trees a Joshua presentation DATA STRUCTURES.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Binary Trees In computer science, a binary tree is a tree data structure in which each node has at most two children, which are referred to as the left.
Data Structures Hanoch Levi and Uri Zwick March 2011 Lecture 3 Dynamic Sets / Dictionaries Binary Search Trees.
Trees. What is a tree? You know…  tall  green  leafy  possibly fruit  branches  roots  I’m sure you’ve seen them.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
2/11/ IT 179 Recursive Definition of Tree Structures 1.Empty is a tree; the root is null 2.A node points to a finite number of the roots of some.
Lab 4 Due date: March 29. Linked Representation Each binary tree node is represented as an object whose data type is binaryTreeNode. The space required.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
Week 7 - Wednesday.  What did we talk about last time?  Recursive running time  Master Theorem  Symbol tables.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture13.
Lecture 19: Binary Trees reading: 17.1 – 17.3
Basic Tree Data Structures
Building Java Programs
Week 6 - Wednesday CS221.
Binary Trees "The best time to plant a tree is twenty years ago. The second best time is now." -Chinese proverb Real programmmers always confuse Christmas.
Tree.
Trees Tree nomenclature Implementation strategies Traversals
Trees Trees are a very useful data structure. Many different kinds of trees are used in Computer Science. We shall study just a few of these.
Trees.
אינדקסינג והשינג (indexing & hashing)
Chapter 20: Binary Trees.
Data Structures and Database Applications Binary Trees in C#
TREES General trees Binary trees Binary search trees AVL trees
SQL בסיסי – הגדרה אינדוקטיבית
תירגול 14: מבני נתונים דינאמיים
Chapter 21: Binary Trees.
Trees.
Binary Tree Traversal Methods
General Trees & Binary Trees
Data Structures, CS, TAU, Splay Tree
Marina Kogan Sadetsky –
Binary Tree Traversal Methods
Trees.
Topic 18 Binary Trees "A tree may grow a thousand feet tall, but its leaves will return to its roots." -Chinese Proverb.
מבוא לתכנות ב- Java תרגול 10 - רשימות מקושרות.
Lecture 12 CS203 1.
Binary Tree Traversal Methods
CMSC 202 Trees.
Announcements: Assignment #2 is posted, due Wed. Oct. 7 (no extension). Lab 4 is posted. No office hours Friday Oct. 2. Let me know if you have any suggestions.
General Trees & Binary Trees
Building Java Programs
Chapter 20: Binary Trees.
Tree.
Trees.
Presentation transcript:

Tirgul 12 Trees 1

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

Binary trees Each node has at most 2 children

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; }

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

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() ); {

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

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?

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

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

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.

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);

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

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);

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

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);

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

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);

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

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.

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

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) {

שאלה ממועד ב' 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 הוא מספר הערכים בעץ).

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; }

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(); }

ד. (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 נקודות) חשבו את סיבוכיות כל אחת מהשיטות אשר כתבתם בסעיף ג' ו-ד'.