Skip to content

Commit 151edde

Browse files
authored
Update 1123-lowest-common-ancestor-of-deepest-leaves.js
1 parent 279caa1 commit 151edde

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

1123-lowest-common-ancestor-of-deepest-leaves.js

+33
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,36 @@
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+
* @return {TreeNode}
12+
*/
13+
const lcaDeepestLeaves = function(root) {
14+
let maxDepth = 0, lcaNode = null
15+
16+
function lca(node, depth) {
17+
if(node == null) return depth - 1
18+
maxDepth = Math.max(depth, maxDepth)
19+
const left = lca(node.left, depth + 1)
20+
const right = lca(node.right, depth + 1)
21+
if(left === maxDepth && right === maxDepth) {
22+
lcaNode = node
23+
}
24+
return Math.max(left, right)
25+
}
26+
27+
lca(root, 0)
28+
return lcaNode
29+
};
30+
31+
32+
// another
33+
134
/**
235
* Definition for a binary tree node.
336
* function TreeNode(val) {

0 commit comments

Comments
 (0)