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)
  • 相关阅读:
    sbt设置
    scala高级内容(二)
    scala高级内容(一) Case Class
    xubuntu手记
    ScalaTour 2.函数
    ScalaTour-1.基础
    springboot对jsp模板引擎的支持
    springboot对Thymeleaf模板引擎的支持
    SpringBoot接收参数的七种方式
    idea快捷代码提示和修改
  • 原文地址:https://www.cnblogs.com/yucen/p/9912023.html
Copyright © 2011-2022 走看看