Geeksforgeeks

Error

×

Leaderboard

Showing:

Handle | Score |
---|---|

@Ibrahim Nash | 6560 |

@blackshadows | 6400 |

@mb1973 | 5777 |

@Quandray | 5271 |

@akhayrutdinov | 5111 |

@saiujwal13083 | 5074 |

@kirtidee18 | 4356 |

@sanjay05 | 3762 |

@mantu_singh | 3638 |

@gfgaccount | 3601 |

@marius_valentin_dragoi | 3525 |

Complete Leaderboard | |

Handle | Score |

@anish5256 | 991 |

@vimleshpratapsingh321 | 980 |

@skj7 | 871 |

@akhileshkumar562002 | 862 |

@pradeeppatidar1999 | 840 |

@kanewilliamson123 | 837 |

@pd420786 | 813 |

@infilooop | 800 |

@bunnybug320 | 796 |

@smitabose7826 | 784 |

@virgat | 768 |

Complete Leaderboard |

Given a binary tree and two node values your task is to find the minimum distance between them.

**Example 1:**

**Input:
**1
/ \
2 3
a = 2, b = 3**
****Output: **2**
Explanation: **The tree formed is:
1
/ \
2 3
We need the distance between 2 and 3.
Being at node 2, we need to take two
steps ahead in order to reach node 3.
The path followed will be:
2 -> 1 -> 3. Hence, the result is 2.

**Your Task:**

You don't need to read input or print anything. Your task is to complete the function **findDist() **which takes the **root **node of the Tree and the two node values **a** and **b** as input parameters and returns the minimum distance between the nodes represented by the two given node values.

**Expected Time Complexity: **O(N).

**Expected Auxiliary Space: **O(Height of the Tree).

**Constraints:**

1 <= Number of nodes <= 10^{4}

1 <= Data of a node <= 10^{5}

**Note:**The **Input/Ouput** format and **Example** given are used for system's internal purpose, and should be used by a user for **Expected Output** only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.

Show more..

Login to report an issue on this page.

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

YesLoading...

Min distance between two given nodes of a Binary Tree

...