剑指offer 平衡二叉树
问题描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
C++代码实现
思路:递归判断左右子树是否符合条件
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
if (pRoot == NULL)
{
return true;
}
if (deepth(pRoot) == -1)
{
return false;
}
return true;
}
int deepth(TreeNode* pRoot)
{
if (pRoot == NULL)
{
return 0;
}
int l = deepth(pRoot->left);
if (l == -1)
{
return -1;
}
int r = deepth(pRoot->right);
if (r == -1)
{
return -1;
}
int mus = abs(l - r);
if (mus > 1)
{
return -1;
}
return l > r ? l+1:r+1;
}
};
python2代码实现
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot is None:
return True
if self.deepth(pRoot) == -1:
return False
return True
def deepth(self, pRoot):
if pRoot is None:
return 0
l = self.deepth(pRoot.left)
if l == -1:
return -1
r = self.deepth(pRoot.right)
if r == -1:
return -1
if abs(l - r) > 1:
return -1
return l+1 if l > r else r+1