Find distance from root to given node in a binary tree | C ++ program to find distance of a given node from root . ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; Returns - 1 if x doesn 't exist in tree. Else returns distance of x from root ; Base case ; Initialize distance ; Check if x is present at root or in left subtree or right subtree . ; Driver Program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int item ) { Node * temp = new Node ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } int findDistance ( Node * root , int x ) { if ( root == NULL ) return -1 ; int dist = -1 ; if ( ( root -> data == x ) || ( dist = findDistance ( root -> left , x ) ) >= 0 || ( dist = findDistance ( root -> right , x ) ) >= 0 ) return dist + 1 ; return dist ; } int 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 ; }