Find The Distance From Root To Given Node of a Binary Tree.

Objective: Find The Distance From Root To Given Node of a binary tree.

What does Distance means : It means number of edges between two nodes.

Distance from root to given node

Distance from root to given node

Approach:

  • This problem is similar to “Find Path From Root To Given Node
  • Make the following change into that
  • Instead of returning the boolean value return the integer, nodes in the path will return the number = 1 + number returned by pervious node in path .
  • The final return will give you the number of nodes between root and the given leaf node so the distance will be (edges)= number of nodes -1

Complete Code:


Output :

Distance from root to 45 is : 3

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: