Skip to content

Commit 2818931

Browse files
authored
Update 333-largest-bst-subtree.js
1 parent 8122d42 commit 2818931

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

333-largest-bst-subtree.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,22 @@ function helper(node) {
5353
return [-Number.MAX_VALUE, Number.MAX_VALUE, Math.max(left[2], right[2])]
5454
}
5555
}
56+
57+
// another
58+
59+
const largestBSTSubtree = function(root) {
60+
function dfs(node) {
61+
if (!node) return [0, 0, Number.MAX_VALUE, -Number.MAX_VALUE]
62+
const [N1, n1, min1, max1] = dfs(node.left)
63+
const [N2, n2, min2, max2] = dfs(node.right)
64+
const n =
65+
max1 < node.val && min2 > node.val ? n1 + 1 + n2 : -Number.MAX_VALUE
66+
return [
67+
Math.max(N1, N2, n),
68+
n,
69+
Math.min(min1, node.val),
70+
Math.max(max2, node.val)
71+
]
72+
}
73+
return dfs(root)[0]
74+
}

0 commit comments

Comments
 (0)