add new solutions
This commit is contained in:
parent
59b71480d4
commit
71189b61cf
8 changed files with 200 additions and 0 deletions
37
solutions/2/q222/solution.go
Normal file
37
solutions/2/q222/solution.go
Normal 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue