University of Nebraska, Omaha**We aren't endorsed by this school
Course
CSCI 3320
Subject
Computer Science
Date
Dec 16, 2024
Pages
32
Uploaded by DrDolphinPerson939
CSCI3320/8325 Data Structures1CSCI3320/8325: Tree Part I:Tree & BSTJon Youn
What is a TreeIn computer science, a tree is an abstract model of a hierarchical structureA tree consists of nodes with a parent-child relationApplications:Organization chartsFile systemsProgramming environmentsComputers”R”UsSalesR&DManufacturingLaptopsDesktopsUSInternationalEuropeAsiaCanadaA tree is a hierarchical form of data structure as there is a parent-child relationship between the items.
CSCI3320/8325 Data Structures3Concepts on TreesA tree is a collection of nodes.The collection can be empty;Otherwise, a tree consists of a distinguished node r, called the root, and zero or more nonempty (sub)trees T1, T2, …, Tk, each of whose roots are connected by a directed edge from r.The root is the only node without parent.Nodes with no children are known as leaves (also called external nodes).Nodes with the same parent are siblings.A path from node n1to nkis defined as a sequence of node n1, n2, …, nksuch that niis the parent of ni+1for 1 i < k. The length of this path is the number of edges on the path, namely k-1.Notice that in a tree there is exactly one path from the root to each node.
CSCI3320/8325 Data Structures4More Terminologies on TreesFor any node ni, the depthof niis the length of the unique path from the root to ni. Thus, the root is at depth 0.Depth of a nodev is its distance from the root.The heightof niis the length of the longest path from nito a leaf. Thus, all leaves are at height 0. The height of a tree is equal to the height of the root.If there is a path from n1to n2, then n1is an ancestorof n2and n2is a descendantof n1. Ancestors of a node: parent, grandparent, grand-grandparent, etc.Descendant of a node: child, grandchild, grand-grandchild, etc.
CSCI3320/8325 Data Structures5A TreeABCEDHGQKJIPFLMN1.What is the depth of J, A, P ?2.What is the height of E, A, C?3.What is the height of the tree?4.What is the ancestor / descendant of D?5.What is the proper ancestor / descendant of D?
CSCI3320/8325 Data Structures6A TreeABCEDHGQKJIPFLMN1.What are the leaves of the tree?2.What are the sibling of the node F?3.What is the path from A to Q? What is its length?4.Is K F A is a valid path?5.What is the path from D to K?
Tree ADTWe use positions to abstract nodesGeneric methods:Integer len()Boolean is_empty()Iterator positions()Iterator iter()Accessor methods:position root()position parent(p)Iterator children(p)Integer num_children(p)Query methods:Boolean is_leaf(p)Boolean is_root(p)Update method:element replace (p, o)Additional update methods may be defined by data structures implementing the Tree ADT
Binary TreesEach node has at most two children (exactly two for proper binary trees)We call the children of a node left child and right childAlternative recursive definition: a binary tree is eithera tree consisting of a single node, ora tree whose root has an ordered pair of children, each of which is a binary treeclass Node:def __init__(self, data):self.data = dataself.right_child = Noneself.left_child = None
Preorder TraversalA traversal visits the nodes of a tree in a systematic mannerIn a preorder traversal, a node is visited before its descendants Application: print a structured documentdef preorder(node):if node is None:returnprint(node.data)preorder(node.left_child)preorder(node.right_child)532618974
def postorder(node):if node is None:returnpostorder(node.left_child)postorder(node.right_child)print(node.data)215396784Postorder TraversalIn a postorder traversal, a node is visited after its descendantsApplication: compute space used by files in a directory and its subdirectories
Inorder TraversalIn an inorder traversal a node is visited after its left subtree and before its right subtreeApplication: draw a binary treex(v) = inorder rank of vy(v) = depth of v312567984def inorder(node):if node is None:returninorder(node.left_child)print(node.data)inorder(node.right_child)
Tree Traversal ExampleInordertraversalDBHEIALJMFKCGPreordertraversalABDEHICFJLMKGPostordertraversalDHIEBLMJKFGCAABDEHICGFKJLM
Lesson Exercise IDraw a binary tree with the eight nodes A, B, C, D, E, F, G, and H, satisfying the following two conditions at the same time:if we print all the nodes in postorder traversal, the output is F C I B D H G A E;if we print all the nodes in inorder traversal, the output is F D C B I E H A G.
Arithmetic Expression TreeBinary tree associated with an arithmetic expressioninternal nodes: operatorsexternal nodes: operandsExample: arithmetic expression tree for the expression (2 (a -1) +(3 b))+-2a13b
Print Arithmetic ExpressionsSpecialization of an inorder traversalprint operand or operator when visiting nodeprint “(“ before traversing left subtreeprint “)“ after traversing right subtreeAlgorithmprintExpression(v)ifv has a left childprint(“(’’)inOrder(left(v))print(v.element ())ifv has a right childinOrder(right(v))print (“)’’)+-2a13b((2 (a -1)) +(3 b))
Evaluate Arithmetic ExpressionsSpecialization of a postorder traversalrecursive method returning the value of a subtreewhen visiting an internal node, combine the values of the subtreesAlgorithmevalExpr(v)ifis_leaf (v)returnv.element ()elsex evalExpr(left (v))y evalExpr(right (v))operator stored at vreturnx y+-25132
Count nodes in a Binary treedefcountNodes(t):if(t ==None):return0return1 + countNodes(left(t)) +countNodes(right(t))
CSCI3320/8325 Data Structures18Lesson Exercise 2 defcountNodes(t):if(t ==None):return0return1 + countNodes(left(t)) +countNodes(right(t))Write efficient functions that take only a pointer to the root of a binary tree, T, and compute:The number of leaves in TThe number of full nodes in T
Binary Search TreesA binary search tree is a binary tree storing keys (or key-value items) at its nodes and satisfying the following property:Let u, v, and wbe three nodes such that uis in the left subtree of vand wis in the right subtree of v. We have key(u)key(v) key(w)An inorder traversal of a binary search trees visits the keys in increasing order692418<>=
CSCI3320/8325 Data Structures20To search for a key k, we trace a downward path starting at the rootThe next node visited depends on the comparison of kwith the key of the current nodeSearchdef search(self, data):current = self.root_nodewhile True:if current is None:print("Item not found")return Noneelif current.data is data:print("Item found", data)return dataelif current.data > data:current = current.left_childelse:current = current.right_child692418<>=12Example: search(4):
BST: Find the smallest elementdef find_min(self):current = self.root_nodewhile current.left_child:current = current.left_childreturn current.dataCSCI3320/8325 Data Structures21Start at the root and go left as long as there is a left child.628143
BST: Find the largest elementdef find_max(self):current = self.root_nodewhile current.right_child:current = current.right_childreturn current.dataCSCI3320/8325 Data Structures23Start at the root and go right as long as there is a right child.6281437109
InsertionIn order to insert a new element, we start by comparing the value of the new node with the rootif the value is less than the root value, then the new element will be inserted into the left subtree; otherwise, it will be inserted into the right subtree. In this manner, we go to the end of the tree 6924186924185<>>wwExample: insert 5
insert(5)def insert(self, data):node = Node(data)if self.root_node is None:self.root_node = nodereturn self.root_nodeelse:current = self.root_nodeparent = Nonewhile True:parent = currentif node.data < parent.data:current = current.left_childif current is None:parent.left_child = nodereturn self.root_nodeelse:current = current.right_childif current is None:parent.right_child = nodereturn self.root_nodeCSCI3320/8325 Data Structures256924185w
CSCI3320/8325 Data Structures27BST: DeleteAs is common with many data structure, the hardest problem is deletion. The node to be deleted has three conditionsThe node is a leafThe node has one childThe node has two children
CSCI3320/8325 Data Structures28How to Remove a Node?What if the node is a leaf? It can be deleted immediately.513920454951394549
CSCI3320/8325 Data Structures29How to Remove a Node?What if the node has one child? It can be deleted after its parent adjusts a pointer to bypass the node513920454930312551394549303125
CSCI3320/8325 Data Structures30How to Remove a Node?What if the node has two children?The general strategy is to replace the data of this node with the smallest data of the right subtree, and recursively delete the node.6281534638154
BST: Delete a key (1)# delete the key and returns the new rootdefdeleteNode(root, key):ifroot isNone:returnroot# Recursively delete key from the left subtreeifkey < root.key:root.left =deleteNode(root.left, key)# Recursively delete key from the right subtreeelif(key > root.key):root.right =deleteNode(root.right, key)CSCI3320/8325 Data Structures31else:Source from: https://www.geeksforgeeks.org/deletion-in-binary-search-tree/
# This is the node to be deletedelse:# Node with only one child or no childifroot.left isNone:temp =root.rightroot =Nonereturntempelifroot.right isNone:temp =root.leftroot =Nonereturntemp# Node with two children:temp =minValueNode(root.right)root.key =temp.keyroot.right =deleteNode(root.right, temp.key)returnrootCSCI3320/8325 Data Structures32else:BST: Delete a key (2)
CSCI3320/8325 Data Structures34Lesson Exercise 3Show that the maximum number of nodes in a binary tree of height his 2h+1-1.
CSCI3320/8325 Data Structures35Lesson Exercise 4Show the result of inserting 4, 6, 5, 2, 7, 3, 1, 4 into an initially empty binary search tree.Show the result of deleting the root