题目描述
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as: a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
解题思路
这个题目我可以使用递归判断以每个节点为root的树是否为平衡二叉树, 如果有一个不是,那么整个树就不是. 判断方法我们使用获取root 的左右子树的高度, 判断高度差是否大于1
示例代码
func isBalanced(_ root: TreeNode?) -> Bool {
if root == nil {
return true
}
if root?.left == nil && root?.right == nil {
return true
}
if abs(getMaxDeep(root?.left) - getMaxDeep(root?.right)) > 1 {
return false
}
return isBalanced(root?.left) && isBalanced(root?.right)
}
func getMaxDeep(_ root: TreeNode?) -> Int {
if root == nil {
return 0
}
let lf = getMaxDeep(root?.left) + 1
let rt = getMaxDeep(root?.right) + 1
return lf > rt ? lf : rt
}