Skip to content

Commit a736e69

Browse files
authored
Update 865-smallest-subtree-with-all-the-deepest-nodes.js
1 parent 9dad5df commit a736e69

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

865-smallest-subtree-with-all-the-deepest-nodes.js

+34
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,37 @@ function result(node, dist) {
2626
this.node = node;
2727
this.dist = dist;
2828
}
29+
30+
// another
31+
32+
/**
33+
* Definition for a binary tree node.
34+
* function TreeNode(val, left, right) {
35+
* this.val = (val===undefined ? 0 : val)
36+
* this.left = (left===undefined ? null : left)
37+
* this.right = (right===undefined ? null : right)
38+
* }
39+
*/
40+
/**
41+
* @param {TreeNode} root
42+
* @return {TreeNode}
43+
*/
44+
const subtreeWithAllDeepest = function(root) {
45+
let res = null, maxDepth = 0
46+
dfs(root, 0)
47+
48+
return res
49+
50+
function dfs(node, depth) {
51+
if(node == null) return depth - 1
52+
53+
const left = dfs(node.left, depth + 1)
54+
const right = dfs(node.right, depth + 1)
55+
maxDepth = Math.max(maxDepth, left, right)
56+
57+
if(left === maxDepth && right === maxDepth) {
58+
res = node
59+
}
60+
return Math.max(left, right)
61+
}
62+
};

0 commit comments

Comments
 (0)