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
  • 相关阅读:
    java中的成员变量和局部变量
    多线程实现输出当前时间,和猜数字游戏
    JDBC
    jQuery和原生JS的对比
    JavaScript有趣的知识点
    MySQL的数据类型
    行级元素和块级元素
    重定向和请求转发的区别
    JSP九大内置对象
    Python练习
  • 原文地址:https://www.cnblogs.com/asenyang/p/11023795.html
Copyright © 2011-2022 走看看