Tree

平衡二叉树

平衡二叉树: 二叉树的每个节点的左右子树的高度差的绝对值不超过1

  • 判断一棵树是否是平衡二叉树
例子:
输入: 给定二叉树 [3,9,20,null,null,15,7] 
输出: true

输入: 给定二叉树 [1,2,2,3,3,null,null,4,4]
输出: false
var heightArr  = map[*TreeNode]int32{}

func isBalanced(root *TreeNode) bool {
	if root == nil {
		return true
	} else {
		return math.Abs(float64(height(root.Left) - height(root.Right))) <= 1 &&
			isBalanced(root.Left) && isBalanced(root.Right)
	}
}

func height(root *TreeNode) int32 {
	if h, ok := heightArr[root]; ok {
		return h
	}
	if root == nil {
		return 0
	} else {
		return int32(math.Max(float64(height(root.Left)), float64(height(root.Right))) + 1)
	}
}