Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created April 4, 2025 16:15
Show Gist options
  • Save tatsuyax25/3a3b7ccd2df2ce195f4ebbf43b0ec8ff to your computer and use it in GitHub Desktop.
Save tatsuyax25/3a3b7ccd2df2ce195f4ebbf43b0ec8ff to your computer and use it in GitHub Desktop.
Given the root of a binary tree, return the lowest common ancestor of its deepest leaves. Recall that: The node of a binary tree is a leaf if and only if it has no children The depth of the root of the tree is 0. if the depth of a node is d, the de
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var lcaDeepestLeaves = function(root) {
// Variable to track the maximum depth of the tree
let maxDepth = 0;
function findDepth(node, depth) {
if (node !== null) {
// Update the maximum depth seen so far
maxDepth = Math.max(depth, maxDepth);
// Recurse into the left and right subtrees
findDepth(node.left, depth + 1);
findDepth(node.right, depth + 1);
}
}
// First pass to calculate the maximum depth of the tree (0(N))
findDepth(root, 0);
function findLCA(node, depth) {
if (node === null) {
// Return null for an empty node
return null;
}
if (depth === maxDepth) {
// If the current node is at the maximum depth, it's part of the deepest leaves
return node;
}
// Recurse into the left and right subtrees
const leftLCA = findLCA(node.left, depth + 1);
const rightLCA = findLCA(node.right, depth + 1);
// Determine the LCA based on the results from the left and right subtrees
if (leftLCA !== null && rightLCA !== null) {
// If both subtrees have deepest leaves, the current node is their LCA
return node;
} else if (leftLCA !== null) {
// Only the left subtree contains deepest leaves
return leftLCA;
} else if (rightLCA !== null) {
// Only the right subtree contains deepest leaves
return rightLCA;
}
// If neither subtree contains the deepest leaves, return null
return null;
}
// Second pass to find the LCA of the deepest leaves (0(N))
return findLCA(root, 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment