思路:构造一个height函数,计算每个节点的高度,然后递归比较左右子树的高度
123456789101112131415161718
class Solution: def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ # 6 star, 多加练习 # if not root: return True if abs(self.height(root.left)-self.height(root.right)) <= 1: return self.isBalanced(root.left) and self.isBalanced(root.right) return False def height(self, node): if not node: return 0 return max(self.height(node.left), self.height(node.right)) + 1
Go:
1234567891011121314151617181920212223242526272829303132333435
func isBalanced(root *TreeNode) bool { var leftHeight, rightHeight int if root == nil || (root.Left == nil && root.Right == nil) { return true } if root.Left != nil { leftHeight = getHeight(root.Left) + 1 } if root.Right != nil { rightHeight = getHeight(root.Right) + 1 } if math.Abs(float64(leftHeight)-float64(rightHeight)) > 1.0 { return false } return isBalanced(root.Left) && isBalanced(root.Right)}func getHeight(node *TreeNode) int { var leftHeight, rightHeight int if node.Left == nil && node.Right == nil{ return 0 } if node.Left != nil { leftHeight = getHeight(node.Left) + 1 } if node.Right != nil { rightHeight = getHeight(node.Right) + 1 } if leftHeight > rightHeight { return leftHeight } else { return rightHeight }}