Skip to content

Commit f994428

Browse files
authored
Create 1740-find-distance-in-a-binary-tree.js
1 parent 1f7aba8 commit f994428

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {number} p
12+
* @param {number} q
13+
* @return {number}
14+
*/
15+
const findDistance = function (root, p, q) {
16+
if (p == q) return 0
17+
let result = -1
18+
dfs(root, p, q)
19+
return result
20+
21+
/**
22+
The return value means the distance from root node to EITHER p OR q. If
23+
neither p nor q are reachable from the root, return -1.
24+
25+
It is either p or q but not both, because if the root node can reach both
26+
p and q, it is a common ancestor of p and q and the answer should already
27+
be available.
28+
**/
29+
function dfs(root, p, q) {
30+
if (root == null) return -1
31+
32+
let left = dfs(root.left, p, q)
33+
let right = dfs(root.right, p, q)
34+
35+
if (root.val == p || root.val == q) {
36+
// root is p or q, but none of p or q is a descendent of root.
37+
// The distance from root to one of p and q is 0 in this case.
38+
if (left < 0 && right < 0) {
39+
return 0
40+
}
41+
42+
// root is p or q, and root is also the LCA of p and q.
43+
result = 1 + (left >= 0 ? left : right)
44+
return -1
45+
}
46+
47+
// root is neither p nor q, but it is the LCA of p and q.
48+
if (left >= 0 && right >= 0) {
49+
result = left + right + 2
50+
return -1
51+
}
52+
53+
if (left >= 0) {
54+
return left + 1
55+
}
56+
57+
if (right >= 0) {
58+
return right + 1
59+
}
60+
61+
return -1
62+
}
63+
}

0 commit comments

Comments
 (0)