Version 1.0 1 TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.

Slides:



Advertisements
Similar presentations
TREES Chapter 6. Trees - Introduction  All previous data organizations we've studied are linear—each element can have only one predecessor and successor.
Advertisements

Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees, Binary Trees, and Binary Search Trees COMP171.
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
© 2006 Pearson Addison-Wesley. All rights reserved11 A-1 Chapter 11 Trees.
Chapter 12 Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define trees as data structures Define the terms.
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.
TCSS 342 BST v1.01 BST addElement To addElement(), we essentially do a find( ). When we reach a null pointer, we create a new node there. void addElement(Object.
CSC 2300 Data Structures & Algorithms February 6, 2007 Chapter 4. Trees.
Binary Trees Chapter 6.
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
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.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
S EARCHING AND T REES COMP1927 Computing 15s1 Sedgewick Chapters 5, 12.
Trees CSCI Objectives Define trees as data structures Define the terms associated with trees Discuss the possible implementations of trees Analyze.
Chapter 19 Implementing Trees and Priority Queues Fundamentals of Java.
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,
Chapter 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
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.
Data Structures and Algorithm Analysis Trees Lecturer: Jing Liu Homepage:
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.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
Trees  Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
Data Structures – Week #5 Trees (Ağaçlar). December 4, 2015Borahan Tümer, Ph.D.2 Trees (Ağaçlar) Toros GöknarıAvrupa Göknarı.
Introduction to Trees IT12112 Lecture 05 Introduction Tree is one of the most important non-linear data structures in computing. It allows us to implement.
M180: Data Structures & Algorithms in Java Trees & Binary Trees Arab Open University 1.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
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.
1 Chapter 4 Trees Basic concept How tree are used to implement the file system How tree can be used to evaluate arithmetic expressions How to use trees.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
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.
24 January Trees CSE 2011 Winter Trees Linear access time of linked lists is prohibitive  Does there exist any simple data structure for.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
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.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
TREES General trees Binary trees Binary search trees AVL trees Balanced and Threaded trees.
Trees CSIT 402 Data Structures II 1. 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical.
1 CMSC 341 Introduction to Trees Textbook sections:
DS.T.1 Trees Chapter 4 Overview Tree Concepts Traversals Binary Trees Binary Search Trees AVL Trees Splay Trees B-Trees.
TREES From root to leaf. Trees  A tree is a non-linear collection  The elements are in a hierarchical arrangement  The elements are not accessible.
CSE 373 Data Structures Lecture 7
Trees Chapter 15.
CC 215 Data Structures Trees
CMSC 341 Introduction to Trees 8/3/2007 CMSC 341 Tree Intro.
CMSC 341 Introduction to Trees.
CSE 373 Data Structures Lecture 7
Binary Search Trees Why this is a useful data structure. Terminology
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Ch. 11 Trees 사실을 많이 아는 것 보다는 이론적 틀이 중요하고, 기억력보다는 생각하는 법이 더 중요하다.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Trees CSE 373 Data Structures.
Trees.
Binary Trees, Binary Search Trees
Trees.
CMSC 341 Introduction to Trees CMSC 341 Tree Intro.
BST Insert To insert an element, we essentially do a find( ). When we reach a NULL pointer, we create a new node there. void BST::insert(const Comp &
Trees are Everywhere family genealogy organizational charts
Trees CSE 373 Data Structures.
Trees CSE 373 Data Structures.
Binary Trees, Binary Search Trees
Presentation transcript:

version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees

2 Chapter Objectives Learn about tree structures definition traversal operations Learn about how to implement tree structures linked structures simulated links using arrays computational strategy using arrays Learn about binary search trees

3 Trees A tree is a collection of nodes. The collection is either empty OR It consists of a distinguished node r, called a root and zero or more non-empty distinct (sub)trees T 1, …, T k, each of whose root are connected by a directed edge from r. Represents commonly found hierarchical structure

4 figure 9.1 Tree terminology

5 root of each subtree is a child of r. r is the parent of each subtree root. Visualizing Trees r T1T1 T2T2 T3T3

6 Tree terminology A leaf has no children. An internal node has at least one child. Siblings have the same parent. grandparent, grandchild, ancestor, descendant A path is a sequence of nodes n 1, n 2, …, n k such that n i is the parent of n i+1 for 1  i < k. The length of a path is the number of edges in the path. The depth of a node is the length of the path from the root to the node. (Starts at zero!) The height of a tree: length of the longest path from root to a leaf.

7 figure 9.2 Path length and level

8 Balanced and unbalanced trees

9 Tree example C:\ hw2 tcss342 hw1proj1 MyMail school D101 pers one.javacalc.java test.java

10 Trees are Everywhere family genealogy organizational charts corporate government military folders/files on a computer compilers: parse tree a = (b + c) * d; d+ *a = cb

11 Tree traversals preorder traversal public void preorderPrintTree(TreeNode tnode){ tnode.print(); // preorder spot! for each child c of tnode preorderPrintTree(c); } postorder traversal public void postorderPrintTree(TreeNode tnode){ for each child c of tnode postorderPrintTree(c); tnode.print(); // postorder spot! }

12 Tree traversals postorder traversal node count. public int numNodes(TreeNode tnode) { if (tnode == null) return 0; else { int sum = 0; for each child c of tnode sum += numNodes(c); return 1 + sum; }

13 Tree Implementation:First child/next sibling public class TreeNode { T element; TreeNode firstChild; TreeNode nextSibling; } C:\ hw2 tcss342 hw1proj1 MyMail school D101 pers one.javacalc.java test.java

14 Level order traversal Stated in pseudocode, the algorithm for a level order traversal of a tree is:

15 Binary tree impl. with links A binary tree is a tree where all nodes have at most two children. class BinaryTreeNode { T element; BinaryTreeNode left; BinaryTreeNode right; }

16 BinaryTree constructors public class BinaryTree { protected int count; protected BinaryTreeNode root; // Creates an empty binary tree. public BinaryTree(){...} // Creates a binary tree with the specified element // as its root. public BinaryTree (T element) {... } // Constructs a binary tree from the two specified // binary trees. public BinaryTree (T element, BinaryTree leftSubtree, BinaryTree rightSubtree) {...}

17 The operations on a binary tree

18 Simulated link strategy for array implementation of trees

19 Computational strategy for array implementation of trees

20 Binary Search Trees Associated with each node is a key value that can be compared. Binary search tree property: every node in the left subtree has key whose value is less than the value of the root ’ s key value, and every node in the right subtree has key whose value is greater than the value of the root ’ s key value. the left subtree and the right subtree have the binary search tree property.

21 Example BINARY SEARCH TREE

22 Counterexample NOT A BINARY SEARCH TREE 7 15

23 additional binary search tree operations

24 find on binary search tree Basic idea: compare the value to be found to the key of the root of the tree. If they are equal, we are done. If they are not equal, recurse depending on which half of the tree the value to be found should be in if it is there. T find(T target, BinaryTreeNode tn) { if (tn == null) return null; else if (target < tn.element) return find(target, tn.left); else if (target > tn.element) return find(target, tn.right); else return tn.element; // match }

25 Adding elements to a binary search tree

26 BST addElement To addElement(), first find( ) its proper location, then insert() it. This recursive implementation recurses down to null nodes, and returns a node which must be assigned to the parent. private BinaryTreeNode insert(T el, BinaryTreeNode tn){ if (tn == null) tn = new BinaryTreeNode (el, null, null); else if (el < tn.element) tn.left = insert(el, tn.left); else if (el > tn.element) tn.right = insert(el, tn.right); else ; // duplicate item; do appropriate thing return tn; } public void addElement(T el){ // you write this! // how would you call insert() here? }

27 findMin, findMax To find the maximum element in the BST, we follow right children until we reach NULL. To find the minimum element in the BST, we follow left children until we reach NULL

28 figure 10.4 Removing elements from a binary search tree

29 BST remove Removing an item disrupts the tree structure. Basic idea: find the node that is to be removed. Then “ fix ” the tree so that it is still a binary search tree. Remove node and replace it with its successor or predecessor (whichever more convenient) Three cases: node has no children node has one child node has two children

30 No children, one child

31 Two children Replace the node with its successor. Then remove the successor from the tree

32 Height of BSTs n-node BST: Worst case depth: n-1. Claim: The maximum number of nodes in a binary tree of height h is 2 h+1 – 1. Proof: The proof is by induction on h. For h = 0, the tree has one node, which is equal to – 1. Suppose the claim is true for any tree of height h. Any tree of height h+1 has at most two subtrees of height h. By the induction hypothesis, this tree has at most 2 (2 h+1 – 1)+1 = 2 h+2 – 1.

33 Height of BSTs, cont ’ d If we have a BST of n nodes and height h, then by the Claim, n  2 h+1 – 1. So, h  log (n+1) – 1.

34 Examining time complexity How long does it take to insert the items 1, 2, 3, …, n (in that order) into a BST? What order would you insert items 1, 2, 3, …, n into a BST so that it is perfectly balanced? How long would this series of n inserts take?

35 Time Complexity A search, insertion, or removal, visits the nodes along a root- to leaf path Time O(1) is spent at each node The worst-case running time of each operation is O(h), where h is the height of the tree With n-node binary tree, height is in n-1 in the worst case (when a binary search tree looks like a sorted sequence) To achieve good running time, we need to keep the tree balanced with O(log n) height

36 Average depth of nodes in a tree. Assumptions: insert items randomly (with equal likelihood); each item is equally likely to be looked up. Average depth for n-node tree  log n Average complexity

37 References Lewis & Chase book, Chapter 12 & 13. Rosen ’ s discrete math book also talks about trees in chapter 9.