问题:
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例:
样例 1:
输入: tree = {1,2,3}
输出: true
样例解释:
如下,是一个平衡的二叉树。
1
/ \
2 3
样例 2:
输入: tree = {3,9,20,#,#,15,7}
输出: true
样例解释:
如下,是一个平衡的二叉树。
3
/ \
9 20
/ \
15 7
python:
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def deepth(self, root):
if root == None:
return 0
return max(self.deepth(root.left), self.deepth(root.right))+1
def isBalanced(self, root):
# write your code here
if root == None:
return True
if(abs(self.deepth(root.left) - self.deepth(root.right)) > 1):
return False
return (self.isBalanced(root.left) and self.isBalanced(root.right))
C++:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
int deepth(TreeNode *root)
{
if(root == NULL)
{
return 0;
}
return (max(deepth(root->left),deepth(root->right)) + 1);
}
bool isBalanced(TreeNode * root) {
// write your code here
if(root == NULL)
{
return true;
}
if(abs(deepth(root->left)- deepth(root->right)) > 1)
{
return false;
}
return (isBalanced(root->left) && isBalanced(root->right));
}
};