How to implement decrease key or change key in Binary Search Tree?
Given a Binary Search Tree, write a function that takes the following three as arguments:
- Root of tree
- Old key value
- 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.