《剑指offer》平衡二叉树

本题来自《剑指offer》 平衡二叉树

题目:

  输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路:

   平衡二叉树的定义:任意节点的左右子树的深度相差不超过1,那么就是一颗平衡二叉树。

  采用递归的方式调用,得到左右子树的深度,两者之间的差度不超过1,则就是,否则不是。

Python Code:

# -*- 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 not pRoot:                       #空数为平衡二叉树
            return True
        left = self.TreeDepth(pRoot.left)   #得到左子树的高度
        right = self.TreeDepth(pRoot.right) #得到右子树的高度
        if abs(left - right) > 1:           #比较左右子树的高度差
            return False                    #若大于1,就不是平衡二叉树
                                            #再递归调用左右子树,也是平衡二叉树,用and
        return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
                                            #函数,返回其树的深度
    def TreeDepth(self,pRoot):
        if not pRoot:                       #如果为空节点就返回0
            return 0
        left = self.TreeDepth(pRoot.left)   #得到左子树的高度
        right = self.TreeDepth(pRoot.right) #得到右子树的高度
        return max(left+1,right+1)          #返回高度叠加
原文地址:https://www.cnblogs.com/missidiot/p/10783699.html