問題:
給定一個二叉樹,確定它是高度平衡的。對於這個問題,一棵高度平衡的二叉樹的定義是:一棵二叉樹中每個節點的兩個子樹的深度相差不會超過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));
}
};