Find distance from root to given node in a binary tree - GeeksforGeeks

24 Jun, 2021
Given the root of a binary tree and a key x in it, find the distance of the given key from the root. Dis­tance means the num­ber of edges between two nodes.
Examples: 
Input : x = 45,
        Root of below tree
        5
      /    \
    10      15
    / \    /  \
  20  25  30   35
       \
       45
Output : Distance = 3             
There are three edges on path
from root to 45.

For more understanding of question,
in above tree distance of 35 is two
and distance of 10 is 1.
Approach: The idea is to traverse the tree from the root. Check if x is present at the root or in the left subtree or in the right subtree. We initialize distance as -1 and add 1 to distance for all three cases. 
C++
Java
Python3
C#
Javascript
// C++ program to find distance of a given// node from root.#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{    int data;    Node *left, *right;}; // A utility function to create a new Binary// Tree NodeNode *newNode(int item){    Node *temp = new Node;    temp->data = item;    temp->left = temp->right = NULL;    return temp;} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootint findDistance(Node *root, int x){    // Base case    if (root == NULL)      return -1;     // Initialize distance    int dist = -1;     // Check if x is present at root or in left    // subtree or right subtree.    if ((root->data == x) ||        (dist = findDistance(root->left, x)) >= 0 ||        (dist = findDistance(root->right, x)) >= 0)        return dist + 1;     return dist;} // Driver Program to test above functionsint main(){    Node *root = newNode(5);    root->left = newNode(10);    root->right = newNode(15);    root->left->left = newNode(20);    root->left->right = newNode(25);    root->left->right->right = newNode(45);    root->right->left = newNode(30);    root->right->right = newNode(35);     cout << findDistance(root, 45);    return 0;}
// Java program to find distance of a given// node from root.import java.util.*;class GfG { // A Binary Tree Nodestatic class Node{    int data;    Node left, right;} // A utility function to create a new Binary// Tree Nodestatic Node newNode(int item){    Node temp = new Node();    temp.data = item;    temp.left = null;    temp.right = null;    return temp;} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootstatic int findDistance(Node root, int x){    // Base case    if (root == null)    return -1;     // Initialize distance    int dist = -1;     // Check if x is present at root or in left    // subtree or right subtree.    if ((root.data == x) ||        (dist = findDistance(root.left, x)) >= 0 ||        (dist = findDistance(root.right, x)) >= 0)        return dist + 1;     return dist;} // Driver Program to test above functionspublic static void main(String[] args){    Node root = newNode(5);    root.left = newNode(10);    root.right = newNode(15);    root.left.left = newNode(20);    root.left.right = newNode(25);    root.left.right.right = newNode(45);    root.right.left = newNode(30);    root.right.right = newNode(35);     System.out.println(findDistance(root, 45));}}
# Python3 program to find distance of# a given node from root. # A class to create a new Binary# Tree Nodeclass newNode:    def __init__(self, item):        self.data = item        self.left = self.right = None # Returns -1 if x doesn't exist in tree.# Else returns distance of x from rootdef findDistance(root, x):         # Base case    if (root == None):        return -1     # Initialize distance    dist = -1     # Check if x is present at root or    # in left subtree or right subtree.    if (root.data == x):        return dist + 1    else:        dist = findDistance(root.left, x)        if dist >= 0:            return dist + 1        else:            dist = findDistance(root.right, x)            if dist >= 0:                return dist + 1     return dist # Driver Codeif __name__ == '__main__':     root = newNode(5)    root.left = newNode(10)    root.right = newNode(15)    root.left.left = newNode(20)    root.left.right = newNode(25)    root.left.right.right = newNode(45)    root.right.left = newNode(30)    root.right.right = newNode(35)     print(findDistance(root, 45)) # This code is contributed by PranchalK
// C# program to find distance of a given// node from root.using System; class GfG{     // A Binary Tree Node    class Node    {        public int data;        public Node left, right;    }     // A utility function to create     // a new Binary Tree Node    static Node newNode(int item)    {        Node temp = new Node();        temp.data = item;        temp.left = null;        temp.right = null;        return temp;    }     // Returns -1 if x doesn't exist in tree. Else    // returns distance of x from root    static int findDistance(Node root, int x)    {        // Base case        if (root == null)        return -1;         // Initialize distance        int dist = -1;         // Check if x is present at root or in left        // subtree or right subtree.        if ((root.data == x) ||            (dist = findDistance(root.left, x)) >= 0 ||            (dist = findDistance(root.right, x)) >= 0)            return dist + 1;         return dist;    }     // Driver code    public static void Main(String[] args)    {        Node root = newNode(5);        root.left = newNode(10);        root.right = newNode(15);        root.left.left = newNode(20);        root.left.right = newNode(25);        root.left.right.right = newNode(45);        root.right.left = newNode(30);        root.right.right = newNode(35);         Console.WriteLine(findDistance(root, 45));    }} // This code is contributed by 29AjayKumar
<script> // Javascript program to find distance// of a given node from root. // A Binary Tree Nodeclass Node{         // A utility function to create a    // new Binary Tree Node    constructor(data)    {        this.data = data;        this.left = this.right = null;    }} // Returns -1 if x doesn't exist in tree. Else// returns distance of x from rootfunction findDistance(root, x){         // Base case    if (root == null)        return -1;      // Initialize distance    let dist = -1;      // Check if x is present at root or in left    // subtree or right subtree.    if ((root.data == x) ||        (dist = findDistance(root.left, x)) >= 0 ||        (dist = findDistance(root.right, x)) >= 0)        return dist + 1;      return dist;} // Driver codelet root = new Node(5);root.left = new Node(10);root.right = new Node(15);root.left.left = new Node(20);root.left.right = new Node(25);root.left.right.right = new Node(45);root.right.left = new Node(30);root.right.right = new Node(35); document.write(findDistance(root, 45)); // This code is contributed by rag2127 </script>
Output: 
3
Time Complexity: O(N)
Auxiliary Space: O(1)
YouTubeGeeksforGeeks500K subscribersFind distance from root to given node in a binary tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pavbfn1FHrs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Roshni Agarwal. 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
29AjayKumar
PranchalKatiyar
rohitsingh07052
rag2127
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not