题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
package main import . "nc_tools" /* * 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 } return height(pRoot) != -1 } func height(root *TreeNode) int { if root == nil { return 0 } l := height(root.Left) if l == -1 { return -1 } r := height(root.Right) if r == -1 { return -1 } sub := abs(l, r) if sub > 1 { return -1 } return max(l, r)+1 } func max(x, y int) int { if x > y { return x } return y } func abs(x, y int) int { if x > y { return x-y } return y-x }
思路:
分别计算左右子树的高度,如果高度差大于1,返回-1,即不是平衡二叉树