110. 平衡二叉树
110. 平衡二叉树
题解
思路用分治法,左边平衡 && 右边平衡 && 左右两边高度 <= 1才为true
代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
_,avl:=maxDepth(root)
return avl
}
func maxDepth(root *TreeNode) (int,bool) {
if root==nil{
return 0,true
}
left,leftbool:=maxDepth(root.Left)
right,rightbool:=maxDepth(root.Right)
if leftbool==false || rightbool== false || left-right>1 || right-left>1{
return 0,false
}
if left>right{
return left+1,true
} else {
return right+1,true
}
}