0. 题目
Given a binary tree, determine if it is height-balanced.
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
For this problem, a height-balanced binary tree is defined as:
一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
1. c++版本
#include
class Solution {
public:
int heightOfTree(TreeNode* root) {
if (!root)
return 0;
return max(heightOfTree(root->left), heightOfTree(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if (!root)
return true;
if (abs(heightOfTree(root->left) - heightOfTree(root->right)) > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
};
2. python版本
class Solution(object):
def heightOfTree(self, root):
if not root:
return 0
return max(self.heightOfTree(root.left), self.heightOfTree(root.right)) + 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
if abs(self.heightOfTree(root.left) - self.heightOfTree(root.right)) > 1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
版本2. https://leetcode.com/problems/balanced-binary-tree/discuss/35708/VERY-SIMPLE-Python-solutions-(iterative-and-recursive)-both-beat-90
class Solution(object):
def isBalanced(self, root):
def check(root):
if root is None:
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