36 lines
589 B
Go
36 lines
589 B
Go
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
|