add new solutions

This commit is contained in:
kanna5 2025-12-29 12:16:39 +09:00
parent 59b71480d4
commit 71189b61cf
Signed by: kkyy
GPG key ID: 06332F3965E9B0CF
8 changed files with 200 additions and 0 deletions

View file

@ -0,0 +1,37 @@
package q222
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func count(node *TreeNode, depth int, maxDepth, mdFill *int) bool {
if node == nil {
return false
}
if node.Left == nil && node.Right == nil { // leaf
switch {
case depth == *maxDepth:
*mdFill++
case depth > *maxDepth:
*maxDepth = depth
*mdFill = 1
case depth < *maxDepth:
return true
}
}
return count(node.Left, depth+1, maxDepth, mdFill) ||
count(node.Right, depth+1, maxDepth, mdFill)
}
func countNodes(root *TreeNode) int {
maxdepth, mdFill := 0, 0
count(root, 1, &maxdepth, &mdFill)
if maxdepth == 0 {
return 0
}
return 1<<(maxdepth-1) - 1 + mdFill
}
var _ = countNodes