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
  • 相关阅读:
    VMware Workstation 6.0 正式版公布
    KMyMoney:全体理财好管家
    Bugzilla 3.0 公布
    Brightside:切换工作区的小东西
    QTM-Blogging 客户端
    MDF2ISO-将 MDF 转换为 ISO
    Yakuake 2.8 beta1
    Red Hat 的 Liberation 字体
    Dictman:有效的词典呆板人
    digiKam 0.9.2 Beta 1
  • 原文地址:https://www.cnblogs.com/asenyang/p/11023795.html
Copyright © 2011-2022 走看看