zoukankan      html  css  js  c++  java
  • 剑指Offer 55 二叉树的深度

    二叉树的深度

    输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

     1 # -*- coding:utf-8 -*-
     2 # class TreeNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 class Solution:
     8     def __init__(self):
     9         self.maxlen = 0
    10     
    11     def preOrder(self,root,length):
    12         if root != None:
    13             length += 1
    14             self.preOrder(root.left,length)
    15             self.preOrder(root.right,length)
    16             if root.left == None and root.right == None:
    17                 self.maxlen = max(self.maxlen,length)
    18             length -= 1
    19         
    20     def TreeDepth(self, pRoot):
    21         if pRoot == None:
    22             return 0
    23         self.preOrder(pRoot,0)
    24         return self.maxlen
    25         # write code here

    平衡二叉树

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

     1 # -*- coding:utf-8 -*-
     2 # class TreeNode:
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 class Solution:
     8     def __init__(self):
     9         self.isBalanced = True
    10         
    11     def height(self,root):
    12         if root == None or not self.isBalanced:
    13             return 0
    14         left = self.height(root.left)
    15         right = self.height(root.right)
    16         if abs(left - right) > 1:
    17             self.isBalanced = False
    18         return 1 + max(left,right)
    19         
    20     def IsBalanced_Solution(self, pRoot):
    21         self.height(pRoot)
    22         return self.isBalanced
    23         # write code here
  • 相关阅读:
    scrapy 断点续爬
    Tornado
    python 列表去重的几种方法
    安装Mysql-python报错EnvironmentError: mysql_config not found
    安装setuptools 报错缺少zlib
    微信小程序-if条件渲染
    微信小程序-遍历列表
    微信小程序-数据绑定
    超强过滤器
    如何在tomcat安装部署php项目
  • 原文地址:https://www.cnblogs.com/asenyang/p/11023795.html
Copyright © 2011-2022 走看看