37 lines
683 B
Go
37 lines
683 B
Go
// Package q110 implements a solution for https://leetcode.com/problems/balanced-binary-tree/
|
|
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
|