zoukankan      html  css  js  c++  java
  • 【剑指Offer】39平衡二叉树

    题目描述

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

    时间限制:1秒;空间限制:32768K;本题知识点:树

    解题思路

    需要用到查找二叉树深度的函数,根据平衡二叉树的性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树,递归求解。

    # -*- 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 == None:
                return True
            a,b = 0,0
            a = self.TreeDepth(pRoot.left)
            b = self.TreeDepth(pRoot.right)
            return abs(a-b)<=1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
        def TreeDepth(self, pRoot):
            # write code here
            if pRoot == None:
                return 0
            a,b,c = 0,0,0
            if pRoot.left!= None:
                a = self.TreeDepth(pRoot.left) + 1
            if pRoot.right!= None:
                b =  self.TreeDepth(pRoot.right) + 1
            if pRoot.left==None and pRoot.right== None:
                c = 1
            return max(a,b,c)
  • 相关阅读:
    drf框架 APView的请求生命周期
    web API接口、restful规范
    vue项目安装插件配置
    vue项目、路由
    day67
    vue组件
    day66
    HDFS(Hadoop Distribute File System)
    JVM运行优化学习笔记
    ELK(检索)
  • 原文地址:https://www.cnblogs.com/yucen/p/9912023.html
Copyright © 2011-2022 走看看