Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Shortest Distance between Two Nodes in BST
Next article icon

Shortest Distance between Two Nodes in BST

Last Updated : 17 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given the root of a Binary Search Tree and two keys, the task is to find the distance between the nodes with the given two keys. Note: The nodes with given keys always exist in the tree.

Shortest-Distance-between-Two-Nodes-in-BST


Approach:

Note: The given approach is optimal only for Binary Search Tree, we have discussed the same problem for simple Binary Tree in Distance between Two Nodes in Binary Tree.

The idea is to start from the root node and check if both the keys are greater than the current node's value, if so, we move to the right child of the current node, else, if both the keys are smaller than the current node's value, we move to the left child of the current node. And for the other case, i.e., one key is smaller and the other key is greater, the current node is Lowest Common Ancestor (LCA), so we find the distance of nodes with given keys from current node and return the sum of distances.

C++
// C++ program to find distance between // two nodes in BST #include <bits/stdc++.h> using namespace std;  class Node {   public:     Node *left, *right;     int key;     Node(int val) {         key = val;         left = right = nullptr;     } };  // Function to find distance of x from root. int distanceFromRoot(Node *root, int x)  {      // if node's value is equal to x return 0.     if (root->key == x)         return 0;      // if node's value is greater than x     // return the distance from left child + 1     else if (root->key > x)         return 1 + distanceFromRoot(root->left, x);      // if node's value is smaller than x     // return the distance from right child + 1     return 1 + distanceFromRoot(root->right, x); }  // Function to find minimum distance between a and b. int distanceBetweenTwoKeys(Node *root, int a, int b) {      // Base Case: return 0 for nullptr.     if (root == nullptr)         return 0;      // Both keys lie in left subtree     if (root->key > a && root->key > b)         return distanceBetweenTwoKeys(root->left, a, b);      // Both keys lie in right subtree     if (root->key < a && root->key < b)         return distanceBetweenTwoKeys(root->right, a, b);      // if keys lie in different subtree     // taking current node as LCA, return the     // sum of distance of keys from current node.     return distanceFromRoot(root, a) + distanceFromRoot(root, b); }  int main() {      // creating the binary search tree     //          5     //        /   \     //       2     12     //      / \    /  \     //     1   3  9    21     //                 /  \     //               19    25      Node *root = new Node(5);     root->left = new Node(2);     root->left->left = new Node(1);     root->left->right = new Node(3);     root->right = new Node(12);     root->right->left = new Node(9);     root->right->right = new Node(21);     root->right->right->left = new Node(19);     root->right->right->right = new Node(25);      int a = 9, b = 25;     cout << distanceBetweenTwoKeys(root, a, b);     return 0; } 
Java
// Java program to find distance between // two nodes in BST class Node {     int data;     Node left, right;      Node(int value) {         data = value;         left = right = null;     } } class GfG {      // Function to find distance of x from root.     static int distanceFromRoot(Node root, int x) {          // if node's value is equal to x return 0.         if (root.data == x)             return 0;          // if node's value is greater than x         // return the distance from left child + 1         else if (root.data > x)             return 1 + distanceFromRoot(root.left, x);          // if node's value is smaller than x         // return the distance from right child + 1         return 1 + distanceFromRoot(root.right, x);     }      // Function to find minimum distance between a and     // b.     static int distanceBetweenTwoKeys(Node root, int a,                                       int b) {          // Base Case: return 0 for null.         if (root == null)             return 0;          // Both keys lie in left subtree         if (root.data > a && root.data > b)             return distanceBetweenTwoKeys(root.left, a, b);          // Both keys lie in right subtree         if (root.data < a && root.data < b)             return distanceBetweenTwoKeys(root.right, a, b);          // if keys lie in different subtree         // taking current node as LCA, return the         // sum of distance of keys from current node.         return distanceFromRoot(root, a)             + distanceFromRoot(root, b);     }      public static void main(String[] args) {          // creating the binary search tree         //          5         //        /   \         //       2     12         //      / \    /  \         //     1   3  9    21         //                /  \         //              19    25          Node root = new Node(5);         root.left = new Node(2);         root.left.left = new Node(1);         root.left.right = new Node(3);         root.right = new Node(12);         root.right.left = new Node(9);         root.right.right = new Node(21);         root.right.right.left = new Node(19);         root.right.right.right = new Node(25);          int a = 9, b = 25;         System.out.println(             distanceBetweenTwoKeys(root, a, b));     } } 
Python
# Python3 program to find distance between # two nodes in BST  class Node:     def __init__(self, val):         self.key = val         self.left = None         self.right = None  # Function to find distance of x from root. def distanceFromRoot(root, x):      # if node's value is equal to x return 0.     if root.key == x:         return 0      # if node's value is greater than x     # return the distance from left child + 1     elif root.key > x:         return 1 + distanceFromRoot(root.left, x)      # if node's value is smaller than x     # return the distance from right child + 1     return 1 + distanceFromRoot(root.right, x)  # Function to find minimum distance between a and b. def distanceBetweenTwoKeys(root, a, b):      # Base Case: return 0 for None.     if root is None:         return 0      # Both keys lie in left subtree     if root.key > a and root.key > b:         return distanceBetweenTwoKeys(root.left, a, b)      # Both keys lie in right subtree     if root.key < a and root.key < b:         return distanceBetweenTwoKeys(root.right, a, b)      # if keys lie in different subtree     # taking current node as LCA, return the     # sum of distance of keys from current node.     return distanceFromRoot(root, a) + distanceFromRoot(root, b)   if __name__ == '__main__':      # creating the binary search tree     #          5     #        /   \     #       2     12     #      / \    /  \     #     1   3  9    21     #                 /  \     #               19    25      root = Node(5)     root.left = Node(2)     root.left.left = Node(1)     root.left.right = Node(3)     root.right = Node(12)     root.right.left = Node(9)     root.right.right = Node(21)     root.right.right.left = Node(19)     root.right.right.right = Node(25)      a, b = 9, 25     print(distanceBetweenTwoKeys(root, a, b)) 
C#
// C# program to find distance between // two nodes in BST using System;  class Node {     public Node left, right;     public int key;      public Node(int val) {         key = val;         left = right = null;     } }  class GfG {        // Function to find distance of x from root.     static int distanceFromRoot(Node root, int x) {                // if node's value is equal to x return 0.         if (root.key == x)             return 0;          // if node's value is greater than x         // return the distance from left child + 1         else if (root.key > x)             return 1 + distanceFromRoot(root.left, x);          // if node's value is smaller than x         // return the distance from right child + 1         return 1 + distanceFromRoot(root.right, x);     }      // Function to find minimum distance between a and b.     static int distanceBetweenTwoKeys(Node root, int a, int b) {                // Base Case: return 0 for null.         if (root == null)             return 0;          // Both keys lie in left subtree         if (root.key > a && root.key > b)             return distanceBetweenTwoKeys(root.left, a, b);          // Both keys lie in right subtree         if (root.key < a && root.key < b)             return distanceBetweenTwoKeys(root.right, a, b);          // if keys lie in different subtree         // taking current node as LCA, return the         // sum of distance of keys from current node.         return distanceFromRoot(root, a) + distanceFromRoot(root, b);     }      static void Main(string[] args) {                // creating the binary search tree         //          5         //        /   \         //       2     12         //      / \    /  \         //     1   3  9    21         //                 /  \         //               19    25          Node root = new Node(5);         root.left = new Node(2);         root.left.left = new Node(1);         root.left.right = new Node(3);         root.right = new Node(12);         root.right.left = new Node(9);         root.right.right = new Node(21);         root.right.right.left = new Node(19);         root.right.right.right = new Node(25);          int a = 9, b = 25;         Console.WriteLine(distanceBetweenTwoKeys(root, a, b));     } } 
JavaScript
// JavaScript program to find distance between // two nodes in BST  class Node {     constructor(val) {         this.key = val;         this.left = null;         this.right = null;     } }  // Function to find distance of x from root. function distanceFromRoot(root, x) {      // if node's value is equal to x return 0.     if (root.key === x)         return 0;      // if node's value is greater than x     // return the distance from left child + 1     else if (root.key > x)         return 1 + distanceFromRoot(root.left, x);      // if node's value is smaller than x     // return the distance from right child + 1     return 1 + distanceFromRoot(root.right, x); }  // Function to find minimum distance between a and b. function distanceBetweenTwoKeys(root, a, b) {      // Base Case: return 0 for null.     if (root === null)         return 0;      // Both keys lie in left subtree     if (root.key > a && root.key > b)         return distanceBetweenTwoKeys(root.left, a, b);      // Both keys lie in right subtree     if (root.key < a && root.key < b)         return distanceBetweenTwoKeys(root.right, a, b);      // if keys lie in different subtree     // taking current node as LCA, return the     // sum of distance of keys from current node.     return distanceFromRoot(root, a) + distanceFromRoot(root, b); }  //              5 //            /   \ //           2     12 //          / \    /  \ //         1   3  9    21 //                     /  \ //                   19    25  let root = new Node(5); root.left = new Node(2); root.left.left = new Node(1); root.left.right = new Node(3); root.right = new Node(12); root.right.left = new Node(9); root.right.right = new Node(21); root.right.right.left = new Node(19); root.right.right.right = new Node(25);  const a = 9, b = 25; console.log(distanceBetweenTwoKeys(root, a, b)); 

Output
3

Time Complexity: O(h), where h is the height of the Binary Search Tree.
Auxiliary Space: O(h), for recursive stack of size h.


Next Article
Shortest Distance between Two Nodes in BST

S

Shweta Singh
Improve
Article Tags :
  • Misc
  • Binary Search Tree
  • DSA
  • Amazon
  • Qualcomm
  • Samsung
  • Ola Cabs
  • LCA
Practice Tags :
  • Amazon
  • Ola Cabs
  • Qualcomm
  • Samsung
  • Binary Search Tree
  • Misc

Similar Reads

    Binary Search Tree
    A Binary Search Tree (BST) is a type of binary tree data structure in which each node contains a unique key and satisfies a specific ordering property:All nodes in the left subtree of a node contain values strictly less than the node’s value. All nodes in the right subtree of a node contain values s
    4 min read
    Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
    Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward.The left subtree of a node contains only node
    3 min read
    Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
    Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST.Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is fo
    15 min read
    Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
    Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios:Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BSTDeleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node w
    10 min read
    Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: A Binary Search TreeOutput: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 1
    10 min read
    Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height.Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height.Input: Output: Explanation: The above u
    10 min read
    Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences