55-02 判断平衡二叉树
题目
输入一课二叉树的根结点,判断该树是不是平衡二叉树。如果二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
C++ 题解
采用递归的方法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == nullptr)
return true;
if(abs(getDepth(root->left) - getDepth(root->right)) > 1)
return false;
return isBalanced(root->left) && isBalanced(root->right);
}
int getDepth(TreeNode* root)
{
if (root==nullptr)
return 0;
return max(getDepth(root->left),getDepth(root->right)) +1;
}
};
python 题解
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
left = self.GetDepth(root.left)
right = self.GetDepth(root.right)
if(abs(left - right) > 1):
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def GetDepth(self,proot):
if proot == None:
return 0
left = self.GetDepth(proot.left)
right = self.GetDepth(proot.right)
return max(left,right) + 1