Skip to content
Related Articles

Related Articles

Improve Article

Shortest distance between two nodes in BST

  • Difficulty Level : Medium
  • Last Updated : 25 May, 2021

Given a Binary Search Tree and two keys in it. Find the distance between two nodes with given two keys. It may be assumed that both keys exist in BST.
 

BST

Examples: 
 

Input:  Root of above tree
         a = 3, b = 9
Output: 4
Distance between 3 and 9 in 
above BST is 4.

Input: Root of above tree
         a = 9, b = 25
Output: 3
Distance between 9 and 25 in 
above BST is 3.

 

We have discussed distance between two nodes in binary tree. The time complexity of this solution is O(n)
In the case of BST, we can find the distance faster. We start from the root and for every node, we do following. 



  1. If both keys are greater than the current node, we move to the right child of the current node.
  2. If both keys are smaller than current node, we move to left child of current node.
  3. If one keys is smaller and other key is greater, current node is Lowest Common Ancestor (LCA) of two nodes. We find distances of current node from two keys and return sum of the distances.

 

C++




// CPP program to find distance between
// two nodes in BST
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    struct Node* left, *right;
    int key;
};
 
struct Node* newNode(int key)
{
    struct Node* ptr = new Node;
    ptr->key = key;
    ptr->left = ptr->right = NULL;
    return ptr;
}
 
// Standard BST insert function
struct Node* insert(struct Node* root, int key)
{
    if (!root)
        root = newNode(key);
    else if (root->key > key)
        root->left = insert(root->left, key);
    else if (root->key < key)
        root->right = insert(root->right, key);
    return root;
}
 
// This function returns distance of x from
// root. This function assumes that x exists
// in BST and BST is not NULL.
int distanceFromRoot(struct Node* root, int x)
{
    if (root->key == x)
        return 0;
    else if (root->key > x)
        return 1 + distanceFromRoot(root->left, x);
    return 1 + distanceFromRoot(root->right, x);
}
 
// Returns minimum distance between a and b.
// This function assumes that a and b exist
// in BST.
int distanceBetween2(struct Node* root, int a, int b)
{
    if (!root)
        return 0;
 
    // Both keys lie in left
    if (root->key > a && root->key > b)
        return distanceBetween2(root->left, a, b);
 
    // Both keys lie in right
    if (root->key < a && root->key < b) // same path
        return distanceBetween2(root->right, a, b);
 
    // Lie in opposite directions (Root is
    // LCA of two nodes)
    if (root->key >= a && root->key <= b)
        return distanceFromRoot(root, a) +
               distanceFromRoot(root, b);
}
 
// This function make sure that a is smaller
// than b before making a call to findDistWrapper()
int findDistWrapper(Node *root, int a, int b)
{
   if (a > b)
     swap(a, b);
   return distanceBetween2(root, a, b);  
}
 
// Driver code
int main()
{
    struct Node* root = NULL;
    root = insert(root, 20);
    insert(root, 10);
    insert(root, 5);
    insert(root, 15);
    insert(root, 30);
    insert(root, 25);
    insert(root, 35);
    int a = 5, b = 55;
    cout << findDistWrapper(root, 5, 35);
    return 0;
}

Java




// Java program to find distance between
// two nodes in BST
class GfG {
 
static class Node {
    Node left, right;
    int key;
}
 
static Node newNode(int key)
{
    Node ptr = new Node();
    ptr.key = key;
    ptr.left = null;
    ptr.right = null;
    return ptr;
}
 
// Standard BST insert function
static Node insert(Node root, int key)
{
    if (root == null)
        root = newNode(key);
    else if (root.key > key)
        root.left = insert(root.left, key);
    else if (root.key < key)
        root.right = insert(root.right, key);
    return root;
}
 
// This function returns distance of x from
// root. This function assumes that x exists
// in BST and BST is not NULL.
static int distanceFromRoot(Node root, int x)
{
    if (root.key == x)
        return 0;
    else if (root.key > x)
        return 1 + distanceFromRoot(root.left, x);
    return 1 + distanceFromRoot(root.right, x);
}
 
// Returns minimum distance beween a and b.
// This function assumes that a and b exist
// in BST.
static int distanceBetween2(Node root, int a, int b)
{
    if (root == null)
        return 0;
 
    // Both keys lie in left
    if (root.key > a && root.key > b)
        return distanceBetween2(root.left, a, b);
 
    // Both keys lie in right
    if (root.key < a && root.key < b) // same path
        return distanceBetween2(root.right, a, b);
 
    // Lie in opposite directions (Root is
    // LCA of two nodes)
    if (root.key >= a && root.key <= b)
        return distanceFromRoot(root, a) + distanceFromRoot(root, b);
         
    return 0;
}
 
// This function make sure that a is smaller
// than b before making a call to findDistWrapper()
static int findDistWrapper(Node root, int a, int b)
{
    int temp = 0;
if (a > b)
    {
    temp = a;
    a = b;
    b = temp;
    }
return distanceBetween2(root, a, b);
}
 
// Driver code
public static void main(String[] args)
{
    Node root = null;
    root = insert(root, 20);
    insert(root, 10);
    insert(root, 5);
    insert(root, 15);
    insert(root, 30);
    insert(root, 25);
    insert(root, 35);
    System.out.println(findDistWrapper(root, 5, 35));
}
}

Python3




# Python3 program to find distance between
# two nodes in BST
class newNode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.key = data
        self.left = None
        self.right = None
 
# Standard BST insert function
def insert(root, key):
    if root == None:
        root = newNode(key)
    elif root.key > key:
        root.left = insert(root.left, key)
    elif root.key < key:
        root.right = insert(root.right, key)
    return root
 
# This function returns distance of x from
# root. This function assumes that x exists
# in BST and BST is not NULL.
def distanceFromRoot(root, x):
    if root.key == x:
        return 0
    elif root.key > x:
        return 1 + distanceFromRoot(root.left, x)
    return 1 + distanceFromRoot(root.right, x)
 
# Returns minimum distance beween a and b.
# This function assumes that a and b exist
# in BST.
def distanceBetween2(root, a, b):
    if root == None:
        return 0
 
    # Both keys lie in left
    if root.key > a and root.key > b:
        return distanceBetween2(root.left, a, b)
 
    # Both keys lie in right
    if root.key < a and root.key < b: # same path
        return distanceBetween2(root.right, a, b)
 
    # Lie in opposite directions
    # (Root is LCA of two nodes)
    if root.key >= a and root.key <= b:
        return (distanceFromRoot(root, a) +
                distanceFromRoot(root, b))
 
# This function make sure that a is smaller
# than b before making a call to findDistWrapper()
def findDistWrapper(root, a, b):
    if a > b:
        a, b = b, a
    return distanceBetween2(root, a, b)
 
# Driver code
if __name__ == '__main__':
    root = None
    root = insert(root, 20)
    insert(root, 10)
    insert(root, 5)
    insert(root, 15)
    insert(root, 30)
    insert(root, 25)
    insert(root, 35)
    a, b = 5, 55
    print(findDistWrapper(root, 5, 35))
 
# This code is contributed by PranchalK

C#




// C# program to find distance between
// two nodes in BST
using System;
 
class GfG
{
 
public class Node
{
    public Node left, right;
    public int key;
}
 
static Node newNode(int key)
{
    Node ptr = new Node();
    ptr.key = key;
    ptr.left = null;
    ptr.right = null;
    return ptr;
}
 
// Standard BST insert function
static Node insert(Node root, int key)
{
    if (root == null)
        root = newNode(key);
    else if (root.key > key)
        root.left = insert(root.left, key);
    else if (root.key < key)
        root.right = insert(root.right, key);
    return root;
}
 
// This function returns distance of x from
// root. This function assumes that x exists
// in BST and BST is not NULL.
static int distanceFromRoot(Node root, int x)
{
    if (root.key == x)
        return 0;
    else if (root.key > x)
        return 1 + distanceFromRoot(root.left, x);
    return 1 + distanceFromRoot(root.right, x);
}
 
// Returns minimum distance beween a and b.
// This function assumes that a and b exist
// in BST.
static int distanceBetween2(Node root, int a, int b)
{
    if (root == null)
        return 0;
 
    // Both keys lie in left
    if (root.key > a && root.key > b)
        return distanceBetween2(root.left, a, b);
 
    // Both keys lie in right
    if (root.key < a && root.key < b) // same path
        return distanceBetween2(root.right, a, b);
 
    // Lie in opposite directions (Root is
    // LCA of two nodes)
    if (root.key >= a && root.key <= b)
        return distanceFromRoot(root, a) +
                distanceFromRoot(root, b);
         
    return 0;
}
 
// This function make sure that a is smaller
// than b before making a call to findDistWrapper()
static int findDistWrapper(Node root, int a, int b)
{
    int temp = 0;
if (a > b)
    {
    temp = a;
    a = b;
    b = temp;
    }
return distanceBetween2(root, a, b);
}
 
// Driver code
public static void Main(String[] args)
{
    Node root = null;
    root = insert(root, 20);
    insert(root, 10);
    insert(root, 5);
    insert(root, 15);
    insert(root, 30);
    insert(root, 25);
    insert(root, 35);
    Console.WriteLine(findDistWrapper(root, 5, 35));
}
}
 
// This code contributed by Rajput-Ji

Javascript




<script>
 
// JavaScript program to find distance between
// two nodes in BST
 
     class Node {
            constructor() {
                this.key = 0;
                this.left = null;
                this.right = null;
            }
        }
 
    function newNode(key) {
var ptr = new Node();
        ptr.key = key;
        ptr.left = null;
        ptr.right = null;
        return ptr;
    }
 
    // Standard BST insert function
    function insert(root , key) {
        if (root == null)
            root = newNode(key);
        else if (root.key > key)
            root.left = insert(root.left, key);
        else if (root.key < key)
            root.right = insert(root.right, key);
        return root;
    }
 
    // This function returns distance of x from
    // root. This function assumes that x exists
    // in BST and BST is not NULL.
    function distanceFromRoot(root , x) {
        if (root.key == x)
            return 0;
        else if (root.key > x)
            return 1 + distanceFromRoot(root.left, x);
        return 1 + distanceFromRoot(root.right, x);
    }
 
    // Returns minimum distance beween a and b.
    // This function assumes that a and b exist
    // in BST.
    function distanceBetween2(root , a , b) {
        if (root == null)
            return 0;
 
        // Both keys lie in left
        if (root.key > a && root.key > b)
            return distanceBetween2(root.left, a, b);
 
        // Both keys lie in right
        if (root.key < a && root.key < b) // same path
            return distanceBetween2(root.right, a, b);
 
        // Lie in opposite directions (Root is
        // LCA of two nodes)
        if (root.key >= a && root.key <= b)
            return distanceFromRoot(root, a) +
            distanceFromRoot(root, b);
 
        return 0;
    }
 
    // This function make sure that a is smaller
    // than b before making a call to findDistWrapper()
    function findDistWrapper(root , a , b) {
        var temp = 0;
        if (a > b) {
            temp = a;
            a = b;
            b = temp;
        }
        return distanceBetween2(root, a, b);
    }
 
    // Driver code
     
        var root = null;
        root = insert(root, 20);
        insert(root, 10);
        insert(root, 5);
        insert(root, 15);
        insert(root, 30);
        insert(root, 25);
        insert(root, 35);
        document.write(findDistWrapper(root, 5, 35));
 
// This code is contributed by todaysgaurav
 
</script>

Output:  

4

Time Complexity: O(h) where h is height of Binary Search Tree.
This article is contributed by Shweta Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :