Shortest distance between two nodes in BST

• Difficulty Level : Medium
• Last Updated : 13 Aug, 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. 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 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 functionstruct 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 codeint 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 BSTclass 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 functionstatic 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 between 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 codepublic 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 BSTclass newNode:     # Constructor to create a new node    def __init__(self, data):        self.key = data        self.left = None        self.right = None # Standard BST insert functiondef 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 between 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 codeif __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 BSTusing 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 functionstatic 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 between 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 codepublic 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



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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.