Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

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

Objec­tive: - Find The Dis­tance From Root To Given Node of a binary tree.

What does Dis­tance means : It means num­ber of edges between two nodes.

Distance-from-root-to-given-node

Distance-from-root-to-given-node

Approach:

  • This prob­lem is sim­i­lar to “Find Path From Root To Given Node
  • Make the fol­low­ing change into that
  • Instead of return­ing the boolean value return the inte­ger, nodes in the path will return the num­ber = 1 + num­ber returned by per­vi­ous node in path .
  • The final return will give you the num­ber of nodes between root and the given leaf node so the dis­tance will be (edges)= num­ber of nodes –1

Com­plete Code:


Out­put :

Distance from root to 45 is : 3

You may also like...