Shortest distance between two nodes in BST - GeeksforGeeks

17 Mar, 2022
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. 
If both keys are greater than the current node, we move to the right child of the current node.If both keys are smaller than current node, we move to left child of current node.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.
If both keys are greater than the current node, we move to the right child of the current node.
If both keys are smaller than current node, we move to left child of current node.
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++
Java
Python3
C#
Javascript
// 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 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 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 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)    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.def 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 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# 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
<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 between 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 review-team@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. 
prerna saini
PranchalKatiyar
Rajput-Ji
Akanksha_Rai
todaysgaurav
sagartomar9927
surinderdawra388
Amazon
LCA
Ola Cabs
Qualcomm
Samsung
Binary Search Tree
Amazon
Samsung
Ola Cabs
Qualcomm
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages of BST over Hash Table
Difference between Binary Tree and Binary Search Tree
Binary Tree to Binary Search Tree Conversion
Merge Two Balanced Binary Search Trees
set vs unordered_set in C++ STL
Sorted Linked List to Balanced BST
Insert a node in Binary Search Tree Iteratively
C Program for Red Black Tree Insertion
How to handle duplicates in Binary Search Tree?
K'th largest element in a stream