• 牛客网-二叉树的深度


    利用二叉树的层次遍历:用计数判断层数是否发生改变

    class Solution:
        def TreeDepth(self, pRoot):
            # write code here
            if pRoot==None:
                return 0
            quene = [pRoot]
            count = 0
            nextcount = 1
            depth = 0
            while(quene):
                root = quene.pop(0)
                count += 1
                if root.left:
                    quene.append(root.left)
                if root.right:
                    quene.append(root.right)
                if count == nextcount:
                    nextcount = len(quene)
                    count = 0
                    depth += 1
            return depth

    利用二叉树的前序遍历:

    #求二叉树的深度
    class Solution:
        def TreeDepth(self, pRoot):
            if pRoot==None:
                return 0
            result = 0
            count = 0
            stack = [(pRoot,1)]
            while(stack):
                root,count = stack.pop()
                if root.right:
                    stack.append((root.right,count+1))
                if root.left:
                    stack.append((root.left,count+1))
                if root.right==None and root.left==None and result<count:
                    result = count
            return result
    

    还有自己写不出来,看了下别人的才发现那么简单的递归

    class Solution:
        def TreeDepth(self, pRoot):
            # write code here
            if pRoot==None:
                return 0
            left = self.TreeDepth(pRoot.left)
            right = self.TreeDepth(pRoot.right)
            return left+1 if left>right else right+1
  • 相关阅读:
    Springboot中使用Scala开发
    aliyun阿里云Maven仓库地址
    css文字滚动
    随笔
    下拉菜单事件
    微信分享
    微信分享功能
    随笔记
    全屏设置
    判定复选框的选中状态
  • 原文地址:https://www.cnblogs.com/ditingz/p/12114654.html
Copyright © 2020-2023  润新知