Skip to content

Commit 6b462a9

Browse files
committed
Add solution #865
1 parent 8246bab commit 6b462a9

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
@@ -672,6 +672,7 @@
672672
862|[Shortest Subarray with Sum at Least K](./0862-shortest-subarray-with-sum-at-least-k.js)|Hard|
673673
863|[All Nodes Distance K in Binary Tree](./0863-all-nodes-distance-k-in-binary-tree.js)|Medium|
674674
864|[Shortest Path to Get All Keys](./0864-shortest-path-to-get-all-keys.js)|Hard|
675+
865|[Smallest Subtree with all the Deepest Nodes](./0865-smallest-subtree-with-all-the-deepest-nodes.js)|Medium|
675676
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
676677
868|[Binary Gap](./0868-binary-gap.js)|Easy|
677678
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 865. Smallest Subtree with all the Deepest Nodes
3+
* https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, the depth of each node is the shortest distance to the root.
7+
*
8+
* Return the smallest subtree such that it contains all the deepest nodes in the original tree.
9+
*
10+
* A node is called the deepest if it has the largest depth possible among any node in the entire
11+
* tree.
12+
*
13+
* The subtree of a node is a tree consisting of that node, plus the set of all descendants of
14+
* that node.
15+
*/
16+
17+
/**
18+
* Definition for a binary tree node.
19+
* function TreeNode(val, left, right) {
20+
* this.val = (val===undefined ? 0 : val)
21+
* this.left = (left===undefined ? null : left)
22+
* this.right = (right===undefined ? null : right)
23+
* }
24+
*/
25+
/**
26+
* @param {TreeNode} root
27+
* @return {TreeNode}
28+
*/
29+
var subtreeWithAllDeepest = function(root) {
30+
return findDepthAndNode(root).node;
31+
32+
function findDepthAndNode(node) {
33+
if (!node) return { depth: 0, node: null };
34+
35+
const left = findDepthAndNode(node.left);
36+
const right = findDepthAndNode(node.right);
37+
38+
if (left.depth === right.depth) {
39+
return { depth: left.depth + 1, node: node };
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)