Shortest Distance between Two Nodes in BST
Last Updated : 17 Dec, 2024
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.
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));
Time Complexity: O(h), where h is the height of the Binary Search Tree.
Auxiliary Space: O(h), for recursive stack of size h.
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