Download presentation
Presentation is loading. Please wait.
1
Non-Linear Structures
Trees
2
A Tree Structure - Each node may have multiple child nodes.
President VP - Mktg VP - Oper VP - Sales CIO Sales Mgr. A Tree Structure - Each node may have multiple child nodes. Show parent/child relationship
3
data data data data data data data data data data data data The height of this tree is 4. Balanced Tree – The depth of all nodes differs by no more than one. Full Tree – Every node (except leaves) has two children. Complete Tree – All levels, except the last one, are full. data data data data
4
Building a Binary Search Tree
Incoming values: 70, 23, 90, 47, 88, 52, 17, 99, 35, 28, 65, 55, 1, 41, 87 70 23 90 17 47 88 99 1 35 52 87 28 41 65 55
5
BTNode - data : Object - left : BTNode - right : BTNode + createBTNode() + getData() : Object + setData() : void + getLeft() : BTNode + setLeft() : void + getRight(): BTNode + setRight(): void
6
Generally, the procedure is the same as for adding a node to the tree.
Follow the path until you run into a node with the value you're searching for. If you reach a null pointer, the value doesn't exist in the tree. Searching a BST
7
70 23 90 47 88 52 17 99 35 28 65 55 1 41 87 Searching a BST
8
Deleting a Node from a BST
After deletion, the tree still must qualify as a BST. Three different cases: The node to be removed is a leaf. The node to be removed has one child. The node to be removed has two children. Deleting a Node from a BST
9
Deleting – Case 1 70 23 90 47 88 52 17 99 35 28 65 55 1 41 87 Delete node containing 1
10
Deleting – Case 2 70 23 90 17 47 88 99 35 52 87 Delete node containing 88. 28 41 65 55
11
Deleting – Case 3 70 23 90 17 47 87 99 35 52 Delete node containing 47
28 41 65 55
12
Deleting – Case 3 (Step 1) 70 23 90 17 41 87 99 35 52 28 47 65 55
13
Deleting – Case 3 (Step 2) 70 23 90 17 41 87 99 35 52 28 65 55
14
BST Deletion Algorithm
Find the node with the value to be deleted (n1). If it's a leaf Delete the node. If it has one child Assign a reference to n1's child to n1's parent. If it has 2 children Find the node with the highest value in the left sub-branch (n2). Swap the values of n1 and n Call delete recursively to remove the original value. BST Deletion Algorithm
15
BST Methods insert – Inserts a node at the proper location.
delete – Deletes a node based on a key. Returns true if the node deleted, and false if the key not found. find – Finds a node based on a key, and returns the data object found in the node. Returns null if the key is not found. clear – Empties the tree of all nodes. BST Methods
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.