Skip to content

Commit 1c698d5

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

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

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

+60
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,63 @@ const findDistance = function (root, p, q) {
6161
return -1
6262
}
6363
}
64+
65+
// another
66+
67+
/**
68+
* Definition for a binary tree node.
69+
* function TreeNode(val, left, right) {
70+
* this.val = (val===undefined ? 0 : val)
71+
* this.left = (left===undefined ? null : left)
72+
* this.right = (right===undefined ? null : right)
73+
* }
74+
*/
75+
/**
76+
* @param {TreeNode} root
77+
* @param {number} p
78+
* @param {number} q
79+
* @return {number}
80+
*/
81+
const findDistance = function (root, p, q) {
82+
let lca = lowestCommonAncestor(root, p, q)
83+
84+
const queue = []
85+
queue.push(lca)
86+
let dp = -1,
87+
dq = -1
88+
let d = 0
89+
while (queue.length && (dp == -1 || dq == -1)) {
90+
for (let k = queue.length; k > 0; k--) {
91+
let node = queue.shift()
92+
if (node.val == p) {
93+
dp = d
94+
}
95+
96+
if (node.val == q) {
97+
dq = d
98+
}
99+
100+
if (node.left != null) {
101+
queue.push(node.left)
102+
}
103+
104+
if (node.right != null) {
105+
queue.push(node.right)
106+
}
107+
}
108+
d++
109+
}
110+
111+
return dp + dq
112+
113+
function lowestCommonAncestor(root, p, q) {
114+
if (root == null || root.val == p || root.val == q) {
115+
return root
116+
}
117+
let left = lowestCommonAncestor(root.left, p, q)
118+
let right = lowestCommonAncestor(root.right, p, q)
119+
120+
return left == null ? right : right == null ? left : root
121+
}
122+
}
123+

0 commit comments

Comments
 (0)