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
- Find the node with minimum value in a Binary Search Tree
- Lowest Common Ancestor in a Binary Search Tree.
- A program to check if a binary tree is BST or not
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Find the largest BST subtree in a given Binary Tree | Set 1
- Inorder Successor in Binary Search Tree
- AVL Tree | Set 1 (Insertion)
- Merge Two Balanced Binary Search Trees
- Binary Tree to Binary Search Tree Conversion
- Optimal Binary Search Tree | DP-24
- Convert a BST to a Binary Tree such that sum of all greater keys is added to every key
- Red-Black Tree | Set 2 (Insert)
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Transform a BST to greater sum tree
- How to handle duplicates in Binary Search Tree?