LeetCode#110.Balanced Binary Tree_Tree/Height/DFS/Recursion
题目
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.
要点
基本概念
root ---> leaves
*Level*
start from 1 ---> += 1
*Depth*
start from 0 ---> += 1
or = Level -1
*Height*
start from max(depth) ---> -= 1
参考资料
解题
解法一
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
“””
def check(root):
if not root: return 0
left = check(root.left)
right = check(root.right)
if left == -1 or right == -1 or abs(left-right) > 1:
return -1
return 1 + max(left, right)
return check(root) != -1
解法二
class Solution(object):
def height(self, root):
if not root: return -1
return 1 + max(self.height(root.left), self.height(root.right))
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
return abs(self.height(root.left) - self.height(root.right)) < 2 \
and self.isBalanced(root.left) \
and self.isBalanced(root.right)