TREES K. Birman’s and G. Bebis’s Slides. Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors.

Slides:



Advertisements
Similar presentations
Binary Trees CSC 220. Your Observations (so far data structures) Array –Unordered Add, delete, search –Ordered Linked List –??
Advertisements

1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Computer Science C++ High School Level By Guillermo Moreno.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
CS 171: Introduction to Computer Science II
Trees Chapter Chapter Contents Tree Concepts Hierarchical Organizations Tree Terminology Traversals of a Tree Traversals of a Binary Tree Traversals.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
1.1 Data Structure and Algorithm Lecture 12 Binary Search Trees Topics Reference: Introduction to Algorithm by Cormen Chapter 13: Binary Search Trees.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Trees Weiss sec (preview) ch. 18 (sort of).
Fundamentals of Python: From First Programs Through Data Structures
1 CS308 Data Structures An application of binary trees: Binary Expression Trees.
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.
ABSTRACT DATA TYPES; LISTS & TREES Lecture 10 CS2110 – Fall 2014.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
CS Data Structures Chapter 5 Trees. Chapter 5 Trees: Outline  Introduction  Representation Of Trees  Binary Trees  Binary Tree Traversals 
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Spring 2010CS 2251 Trees Chapter 6. Spring 2010CS 2252 Chapter Objectives Learn to use a tree to represent a hierarchical organization of information.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
TREES Lecture 12 CS2110 – Fall Announcements  Prelim #1 is tonight!  Olin 155  A-L  5:30  M-Z  5:30  A4 will be posted today  Mid-semester.
Compiled by: Dr. Mohammad Omar Alhawarat
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Trees, Binary Trees, and Binary Search Trees COMP171.
Starting at Binary Trees
TREES. What is a tree ? An Abstract Data Type which emulates a tree structure with a set of linked nodes The nodes within a tree are organized in a hierarchical.
1 Storing Hierarchical Information Lists, Stacks, and Queues represent linear sequences Data often contain hierarchical relationships that cannot be expressed.
Tree Traversals, TreeSort 20 February Expression Tree Leaves are operands Interior nodes are operators A binary tree to represent (A - B) + C.
Trees By P.Naga Srinivasu M.tech,(MBA). Basic Tree Concepts A tree consists of finite set of elements, called nodes, and a finite set of directed lines.
CISC 235 Topic 3 General Trees, Binary Trees, Binary Search Trees.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
1 Trees What is a Tree? Tree terminology Why trees? What is a general tree? Implementing trees Binary trees Binary tree implementation Application of Binary.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
CS Prelim Review – 10/15/09  First prelim is TOMORROW at 7:30 PM  Review session – Tonight 7:30 PM, Phillips 101  Things you should do:  Review every.
TREES Lecture 11 CS2110 – Spring Readings and Homework  Textbook, Chapter 23, 24  Homework: A thought problem (draw pictures!)  Suppose you use.
353 3/30/98 CSE 143 Trees [Sections , 13.6,13.8]
18-1 Chapter 18 Binary Trees Data Structures and Design in Java © Rick Mercer.
1 Trees. 2 Trees Trees. Binary Trees Tree Traversal.
Trees Chapter 15.
CSCE 210 Data Structures and Algorithms
Recursive Objects (Part 4)
Trees Lecture 12 CS2110 – Spring 2017.
Trees Lecture 12 CS2110 – Fall 2017.
Trees Lecture 12 CS2110 – Fall 2016.
Trees.
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
ITEC 2620M Introduction to Data Structures
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Trees Lecture 12 CS2110 – Spring 2018.
Find in a linked list? first last 7  4  3  8 NULL
Trees.
Trees Lecture 9 CS2110 – Fall 2009.
Trees Lecture 12 CS2110 – Fall 2018.
Binary Trees, Binary Search Trees
Trees.
Announcements Prelim 1 on Tuesday! A4 will be posted today
CSC 143 Java Trees.
Trees.
Binary Trees, Binary Search Trees
Trees Lecture 10 CS2110 – Spring 2013.
Presentation transcript:

TREES K. Birman’s and G. Bebis’s Slides

Tree Overview 2  Tree: recursive data structure (similar to list)  Each cell may have zero or more successors (children)  Each cell has exactly one predecessor (parent) except the root, which has none  All cells are reachable from root  Binary tree: tree in which each cell can have at most two children: a left child and a right child General tree Binary tree Not a tree List-like tree

Tree Terminology 3  M is the root of this tree  G is the root of the left subtree of M  B, H, J, N, and S are leaves  N is the left child of P; S is the right child  P is the parent of N  M and G are ancestors of D  P, N, and S are descendants of W  Node J is at depth 2 (i.e., depth = length of path from root = number of edges)  Node W is at height 2 (i.e., height = length of longest path to a leaf)  A collection of several trees is called a...? MGWPJDNHBS

Class for Binary Tree Cells 4 class TreeCell { private T datum; private TreeCell left, right; public TreeCell(T x) { datum = x; } public TreeCell(T x, TreeCell lft, TreeCell rgt) { datum = x; left = lft; right = rgt; } more methods: getDatum, setDatum, getLeft, setLeft, getRight, setRight }... new TreeCell ("hello")... Points to left subtree Points to right subtree

Binary versus general tree  In a binary tree each node has exactly two pointers: to the left subtree, and to the right one  Of course one or both could be null  In a general tree a node can have any number of child nodes  Very useful in some situations... 5

Class for General Tree nodes 6 class GTreeCell { private Object datum; private GTreeCell left; private GTreeCell sibling; appropriate getter and setter methods } General tree Tree represented using GTreeCell  Parent node points directly only to its leftmost child  Leftmost child has pointer to next sibling, which points to next sibling, etc.

Applications of Trees 7  Most languages (natural and computer) have a recursive, hierarchical structure  This structure is implicit in ordinary textual representation  Recursive structure can be made explicit by representing sentences in the language as trees: Abstract Syntax Trees (ASTs)  ASTs are easier to optimize, generate code from, etc. than textual representation  A parser converts textual representations to AST

Grammar for Simple Expressions 8  E  integer  E  ( E + E )  Simple expressions:  An E can be an integer.  An E can be ‘(’ followed by an E followed by ‘+’ followed by an E followed by ‘)’  Set of expressions defined by this grammar is a recursively-defined set  Is language finite or infinite?  Do recursive grammars always yield infinite languages?  Here are some legal expressions:  2  (3 + 34)  ((4+23) + 89)  (( ) + (23 + (34+12)))  Here are some illegal expressions:  (3   The tokens in this grammar are (, +, ), and any integer

Parsing 9  Grammars can be used in two ways  A grammar defines a language (i.e., the set of properly structured sentences)  A grammar can be used to parse a sentence (thus, checking if the sentence is in the language)  To parse a sentence is to build a parse tree  This is much like diagramming a sentence  Example: Show that ((4+23) + 89) is a valid expression E by building a parse tree E ( E ) E+ 89 ( E ) E+ 4 23

Example 10  Expression grammar:  E → integer  E → (E + E)  In textual representation  Parentheses show hierarchical structure  In tree representation  Hierarchy is explicit in the structure of the tree -34 (2 + 3) ((2+3) + (5+7)) TextAST Representation

Recursion on Trees 11  Recursive methods can be written to operate on trees in an obvious way  Base case  empty tree  leaf node  Recursive case  solve problem on left and right subtrees  put solutions together to get solution for full tree

Searching in a Binary Tree 12 public static boolean treeSearch(Object x, TreeCell node) { if (node == null) return false; if (node.datum.equals(x)) return true; return treeSearch(x, node.left) || treeSearch(x, node.right); }  Analog of linear search in lists: given tree and an object, find out if object is stored in tree  Easy to write recursively, harder to write iteratively

Binary Search Tree (BST) 13  If the tree data are ordered – in any subtree,  All left descendents of node come before node  All right descendents of node come after node  This makes it much faster to search public static boolean treeSearch (Object x, TreeCell node) { if (node == null) return false; if (node.datum.equals(x)) return true; if (node.datum.compareTo(x) > 0) return treeSearch(x, node.left); else return treeSearch(x, node.right); }

Building a BST 14  To insert a new item  Pretend to look for the item  Put the new node in the place where you fall off the tree  This can be done using either recursion or iteration  Example  Tree uses alphabetical order  Months appear for insertion in calendar order janfebmaraprmayjunjul

What Can Go Wrong? 15  A BST makes searches very fast, unless…  Nodes are inserted in alphabetical order  In this case, we’re basically building a linked list (with some extra wasted space for the left fields that aren’t being used)  BST works great if data arrives in random order janfebmaraprmayjunjul

Printing Contents of BST 16 Because of the ordering rules for a BST, it’s easy to print the items in alphabetical order  Recursively print everything in the left subtree  Print the node  Recursively print everything in the right subtree /** * Show the contents of the BST in * alphabetical order. */ public void show () { show(root); System.out.println(); } private static void show(TreeNode node) { if (node == null) return; show(node.lchild); System.out.print(node.datum + " "); show(node.rchild); }

Tree Traversals  “Walking” over the whole tree is a tree traversal  This is done often enough that there are standard names  The previous example is an inorder traversal Process left subtree Process node Process right subtree  Note: we’re using this for printing, but any kind of processing can be done  There are other standard kinds of traversals  Preorder traversal  Process node  Process left subtree  Process right subtree  Postorder traversal  Process left subtree  Process right subtree  Process node  Level-order traversal  Not recursive  Uses a queue 17

18 A special kind of binary tree in which: 1. Each leaf node contains a single operand 2. Each nonleaf node contains a single binary operator 3. The left and right subtrees of an operator node represent subexpressions that must be evaluated before applying the operator at the root of the subtree. A Binary Expression Tree is...

19 A Four-Level Binary Expression ‘*’ ‘-’ ‘8’ ‘5’ ‘/’ ‘+’ ‘4’ ‘3’ ‘2’

20 Levels Indicate Precedence The levels of the nodes in the tree indicate their relative precedence of evaluation (we do not need parentheses to indicate precedence). Operations at higher levels of the tree are evaluated later than those below them. The operation at the root is always the last operation performed.

21 A Binary Expression Tree What value does it have? ( ) * 3 = 18 ‘*’ ‘+’ ‘4’ ‘3’ ‘2’

22 Easy to generate the infix, prefix, postfix expressions Infix: ( ( ) * ( ( ) / 3 ) ) Prefix: * / Postfix: / * ‘*’ ‘-’ ‘8’ ‘5’ ‘/’ ‘+’ ‘4’ ‘3’ ‘2’

23 Inorder Traversal: (A + H) / (M - Y) ‘/’ ‘+’ ‘A’ ‘H ’ ‘-’ ‘M’ ‘Y ’ tree Print left subtree firstPrint right subtree last Print second

24 Preorder Traversal: / + A H - M Y ‘/’ ‘+’ ‘A’ ‘H ’ ‘-’ ‘M’ ‘Y ’ tree Print left subtree secondPrint right subtree last Print first

25 ‘/’ ‘+’ ‘A’ ‘H ’ ‘-’ ‘M’ ‘Y ’ tree Print left subtree firstPrint right subtree second Print last Postorder Traversal: A H + M Y - /

Some Useful Methods 26 //determine if a node is a leaf public static boolean isLeaf(TreeCell node) { return (node != null) && (node.left == null) && (node.right == null); } //compute height of tree using postorder traversal public static int height(TreeCell node) { if (node == null) return -1; //empty tree if (isLeaf(node)) return 0; return 1 + Math.max(height(node.left), height(node.right)); } //compute number of nodes using postorder traversal public static int nNodes(TreeCell node) { if (node == null) return 0; return 1 + nNodes(node.left) + nNodes(node.right); }

Useful Facts about Binary Trees 27  2 d = maximum number of nodes at depth d  If height of tree is h  Minimum number of nodes in tree = h + 1  Maximum number of nodes in tree = … + 2 h = 2 h+1 – 1  Complete binary tree  All levels of tree down to a certain depth are completely filled depth Height 2, minimum number of nodes Height 2, maximum number of nodes

Tree with Parent Pointers 28  In some applications, it is useful to have trees in which nodes can reference their parents  Analog of doubly-linked lists

Things to Think About 29  What if we want to delete data from a BST?  A BST works great as long as it’s balanced  How can we keep it balanced? janfebmaraprmayjunjul

Tree Summary 30  A tree is a recursive data structure  Each cell has 0 or more successors (children)  Each cell except the root has at exactly one predecessor (parent)  All cells are reachable from the root  A cell with no children is called a leaf  Special case: binary tree  Binary tree cells have a left and a right child  Either or both children can be null  Trees are useful for exposing the recursive structure of natural language and computer programs