Given a Binary Search Tree, write a function that takes following three as arguments:
1) Root of tree
2) Old key value
3) New Key Value
The function should change old key value to new key value. The function may assume that old key value always exists in Binary Search Tree.
Input: Root of below tree 50 / \ 30 70 / \ / \ 20 40 60 80 Old key value: 40 New key value: 10 Output: BST should be modified to following 50 / \ 30 70 / / \ 20 60 80 / 10
We strongly recommend you to minimize your browser and try this yourself first
The idea is to call delete for old key value, then call insert for new key value. Below is C++ implementation of the idea.
Inorder traversal of the given tree 20 30 40 50 60 70 80 Inorder traversal of the modified tree 10 20 30 50 60 70 80
Time complexity of above changeKey() is O(h) where h is height of BST.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Binary Tree to Binary Search Tree Conversion
- Binary Tree to Binary Search Tree Conversion using STL set
- Difference between Binary Tree and Binary Search Tree
- Binary Search Tree | Set 1 (Search and Insertion)
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Count the Number of Binary Search Trees present in a Binary Tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Find the node with minimum value in a Binary Search Tree
- Lowest Common Ancestor in a Binary Search Tree.
- Inorder Successor in Binary Search Tree
- Optimal Binary Search Tree | DP-24
- How to handle duplicates in Binary Search Tree?
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Construct a Binary Search Tree from given postorder
- Check if given sorted sub-sequence exists in binary search tree
- Find the closest element in Binary Search Tree
- Binary Search Tree insert with Parent Pointer
- Binary Search Tree | Set 2 (Delete)
- Threaded Binary Search Tree | Deletion