170 likes | 259 Views
Learn how to build, search, and delete nodes in a Binary Search Tree (BST) efficiently. Understand the insertion, deletion, and searching algorithms to manipulate BST nodes effectively.
E N D
Non-Linear Structures Trees
President VP - Mktg VP - Oper VP - Sales CIO Sales Mgr.
data data data data data data data data data data data data data data data data
17 52 70 23 90 47 88 87 99 35 28 65 55 1 41 Incoming values: 70, 23, 90, 47, 88, 52, 17, 99, 35, 28, 65, 55, 1, 41, 87 Building a Binary Search Tree
BTNode - data : Object - left : BTNode - right : BTNode + createBTNode() + getData() : Object + setData() : void + getLeft() : BTNode + setLeft() : void + getRight(): BTNode + setRight(): void
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
70 23 90 47 88 52 17 99 35 28 65 55 1 41 87 Searching 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
70 23 90 47 88 52 17 99 35 28 65 55 1 41 87 Deleting – Case 1
70 23 90 47 88 52 17 99 35 28 65 55 41 87 Deleting – Case 2
70 23 90 47 87 52 17 99 35 28 65 55 41 Deleting – Case 3
70 23 90 41 87 52 17 99 35 28 65 55 47 Deleting – Case 3 (Step 1)
70 23 90 41 87 52 17 99 35 28 65 55 Deleting – Case 3 (Step 2)
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 n2. Call delete recursively to remove the original value. BST Deletion Algorithm
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