Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 6496e0c

Browse files
committedMar 21, 2025
Add solution #1123
1 parent 6b462a9 commit 6496e0c

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,7 @@
723723
1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy|
724724
1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy|
725725
1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy|
726+
1123|[Lowest Common Ancestor of Deepest Leaves](./1123-lowest-common-ancestor-of-deepest-leaves.js)|Medium|
726727
1137|[N-th Tribonacci Number](./1137-n-th-tribonacci-number.js)|Easy|
727728
1143|[Longest Common Subsequence](./1143-longest-common-subsequence.js)|Medium|
728729
1161|[Maximum Level Sum of a Binary Tree](./1161-maximum-level-sum-of-a-binary-tree.js)|Medium|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 1123. Lowest Common Ancestor of Deepest Leaves
3+
* https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.
7+
*
8+
* Recall that:
9+
* - The node of a binary tree is a leaf if and only if it has no children
10+
* - The depth of the root of the tree is 0. if the depth of a node is d, the depth of each of
11+
* its children is d + 1.
12+
* - The lowest common ancestor of a set S of nodes, is the node A with the largest depth such
13+
* that every node in S is in the subtree with root A.
14+
*/
15+
16+
/**
17+
* Definition for a binary tree node.
18+
* function TreeNode(val, left, right) {
19+
* this.val = (val===undefined ? 0 : val)
20+
* this.left = (left===undefined ? null : left)
21+
* this.right = (right===undefined ? null : right)
22+
* }
23+
*/
24+
/**
25+
* @param {TreeNode} root
26+
* @return {TreeNode}
27+
*/
28+
var lcaDeepestLeaves = function(root) {
29+
return findDepthAndNode(root).node;
30+
31+
function findDepthAndNode(node) {
32+
if (!node) return { depth: 0, node: null };
33+
34+
const left = findDepthAndNode(node.left);
35+
const right = findDepthAndNode(node.right);
36+
37+
if (left.depth === right.depth) {
38+
return { depth: left.depth + 1, node: node };
39+
}
40+
41+
const deeper = left.depth > right.depth ? left : right;
42+
return { depth: deeper.depth + 1, node: deeper.node };
43+
}
44+
};

0 commit comments

Comments
 (0)
Please sign in to comment.