We keep going to either right subtree or left subtree depending on the value and when we reach a point left or right subtree is null, we put the new node there. The algorithm isn't as simple as it looks. Let's try to visualize how we add a number to an existing BST.
We have attached the node but we still have to exit from the function without doing any damage to the rest of the tree.
This is where the return node; at the end comes in handy. In the case of NULL , the newly created node is returned and attached to the parent node, otherwise the same node is returned without any change as we go up until we return to the root.
In the first case, the node to be deleted is the leaf node. In such a case, simply delete the node from the tree. In the second case, the node to be deleted lies has a single child node. In such a case follow the steps below:. In the third case, the node to be deleted has two children. Course Index Explore Programiz. Start Learning DSA. Popular Tutorials Quicksort Algorithm. Merge Sort Algorithm. Linked List Data Structure. Step 4: Traverse the tree in preorder Step 6: Traverse the tree in postorder.
Step 7: Search the given key element in the BST. Step 8: Delete an element from BST. Step 9: Stop. December 16, December 21, Your email address will not be published. Save my name, email, and website in this browser for the next time I comment. Insertion in Binary Search Tree 2. Step 7: Search the given key element in the BST.
Step 8: Delete an element from BST. Step 9: Stop. Insertion in Binary Search Tree" ;. Search Element in Binary Search Tree" ;. Delete Element in Binary Search Tree" ;.
Exit" ;. Ask a Question. Please log in or register to answer this question.
0コメント