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

    题目描述

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

    样例

    返回深度即可
    

    想法一:
    递归遍历

    class Solution:
        def TreeDepth(self, pRoot):
            if pRoot is None:
                return 0
            return max(1+self.TreeDepth(pRoot.left), 1+self.TreeDepth(pRoot.right))
    

    想法二:
    使用队列,以元组保存节点和节点深度,如果存在左右节点,就将左右节点和当前节点深度加一入队,每次出队一个节点,知道队空。

    class Solution:
        def TreeDepth(self, pRoot):
            # write code here
            return self.depth(pRoot)
    
        def depth(root):
            if root is None:
                return 0
            dq = list()
            dq.append((root, 1))
            while dq:
                node, layer = dq.pop(0)
                deep = layer
                if node.left:
                    dq.append((node.left, layer + 1))
                if node.right:
                    dq.append((node.right, layer + 1))
            return deep
    

    最后

    刷过的LeetCode或剑指offer源码放在Github上了,希望喜欢或者觉得有用的朋友点个star或者follow。
    有任何问题可以在下面评论或者通过私信或联系方式找我。
    联系方式
    QQ:791034063
    Wechat:liuyuhang791034063
    CSDN:https://blog.csdn.net/Sun_White_Boy
    Github:https://github.com/liuyuhang791034063

  • 相关阅读:
    程序员修炼之道阅读笔记02
    第十五周课堂练习-查找最长单词链
    文件读写总结
    第十五周
    暑假总结1
    软件工程课程总结
    第十六周总结
    用户场景分析
    学期课后个人总结
    第十五周总结
  • 原文地址:https://www.cnblogs.com/GF66/p/9785463.html
Copyright © 2011-2022 走看看