Skip to content

Commit 2869cbc

Browse files
authored
Update 1740-find-distance-in-a-binary-tree.js
1 parent 151edde commit 2869cbc

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

1740-find-distance-in-a-binary-tree.js

+40
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,43 @@
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+
return dfs(root, 0)
18+
19+
function dfs(node, depth) {
20+
let res = depth
21+
if (node == null) {
22+
res = 0
23+
} else if(node.val === p || node.val === q) {
24+
let left = dfs(node.left, 1)
25+
let right = dfs(node.right, 1)
26+
res = (left > 0 || right > 0) ? Math.max(left, right) : res
27+
} else {
28+
let left = dfs(node.left, depth + 1)
29+
let right = dfs(node.right, depth + 1)
30+
res = left + right
31+
if(left !== 0 && right !== 0) {
32+
res -= 2 * depth
33+
}
34+
}
35+
return res
36+
}
37+
};
38+
39+
// another
40+
141
/**
242
* Definition for a binary tree node.
343
* function TreeNode(val, left, right) {

0 commit comments

Comments
 (0)