614. Find Distance In a Binary Tree

Given the root of a binary tree and two integers p and q, return the distance between the two nodes with values p and q.

The distance between two nodes in a tree is the number of edges on the shortest path between them.

Example 1:

Input : root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0

Output : 3

Explanation :

There are 3 edges between 5 and 0: 5-3-1-0.

Example 2:

Input : root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7

Output : 2

Explanation :

There are 2 edges between 5 and 7: 5-2-7.

Now Your Turn!

Pick the correct output for the given input

Input : root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 0 <= Node.val <= 109
  • All Node.val are unique.
  • p and q are values in the tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(val) : data(val), left(nullptr), right(nullptr) {}
* };
*/
 
class Solution {
public:
int findDistance(TreeNode* root, int p, int q) {
//Your Code Goes Here
}
};
Test Case

Input:

P
Q
Root