add new solutions
This commit is contained in:
parent
51975f3386
commit
489fa73880
13 changed files with 437 additions and 3 deletions
36
solutions/1/q110/solution.go
Normal file
36
solutions/1/q110/solution.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package q110
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
func abs(a int) int {
|
||||
if a < 0 {
|
||||
return -a
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func isBalancedInternal(node *TreeNode, lvl int) (bool, int) {
|
||||
if node == nil {
|
||||
return true, lvl
|
||||
}
|
||||
|
||||
lBal, lDpth := isBalancedInternal(node.Left, lvl+1)
|
||||
rBal, rDpth := isBalancedInternal(node.Right, lvl+1)
|
||||
dpth := max(lDpth, rDpth)
|
||||
|
||||
if !lBal || !rBal || abs(lDpth-rDpth) > 1 {
|
||||
return false, dpth
|
||||
}
|
||||
return true, dpth
|
||||
}
|
||||
|
||||
func isBalanced(root *TreeNode) bool {
|
||||
ret, _ := isBalancedInternal(root, 0)
|
||||
return ret
|
||||
}
|
||||
|
||||
var _ = isBalanced
|
||||
Loading…
Add table
Add a link
Reference in a new issue