题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
package main
import . "nc_tools"
import "math"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pRoot TreeNode类
* @return bool布尔型
*/
func IsBalanced_Solution(pRoot *TreeNode) bool {
// write code here
if pRoot == nil {
return true
}
leftDeep := calculateDeepth(pRoot.Left)
rightDeep := calculateDeepth(pRoot.Right)
if math.Abs(float64(leftDeep-rightDeep)) > 1 {
return false
}
return IsBalanced_Solution(pRoot.Left) && IsBalanced_Solution(pRoot.Right)
}
func calculateDeepth(node *TreeNode) int {
if node == nil {
return 0
}
return max(calculateDeepth(node.Right), calculateDeepth(node.Left)) + 1
}
func max(left, right int) int {
if left > right {
return left
}
return right
}

腾讯成长空间 5870人发布