判断给定的二叉树是否是平衡二叉树
平衡二叉树的性质为: 要么是一棵空树,要么任何一个节点的左右子树高度差的绝对值不超过 1。
一颗树的高度指的是树的根节点到所有节点的距离中的最大值。
思路:判断每个节点的深度,左右节点进行比较,深度遍历来实现
package main
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
*
* @param root TreeNode类
* @return bool布尔型
*/
func isBalanced(root *TreeNode) bool {
// write code here
if root == nil {
return true
}
ok, _ := GetDepth(root)
return ok
}
func GetDepth(root *TreeNode) (bool, int) {
if root == nil {
return true, 0
}
depth := 0
leftIs, leftDepth := GetDepth(root.Left)
rightIs, rightDepth := GetDepth(root.Right)
if leftIs && rightIs && leftDepth-rightDepth <= 1 && leftDepth-rightDepth >= -1 {
depth = rightDepth + 1
if leftDepth > rightDepth {
depth = leftDepth + 1
}
return true, depth
}
return false, 0
}