VOOZH about

URL: https://www.geeksforgeeks.org/dsa/how-to-implement-decrease-key-or-change-key-in-binary-search-tree/

⇱ How to implement decrease key or change key in Binary Search Tree? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to implement decrease key or change key in Binary Search Tree?

Last Updated : 14 Feb, 2023

Given a Binary Search Tree, write a function that takes the 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.

Example: 

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. 


Output
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. 

Auxiliary Space: O(N),  here N is number of node as we used extra space to store nodes.

Comment
Article Tags: