File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+
1
41
/**
2
42
* Definition for a binary tree node.
3
43
* function TreeNode(val, left, right) {
You can’t perform that action at this time.
0 commit comments