题解 | #把二叉树的深度#

二叉树的深度

http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b

法一:迭代遍历。(借助队列,层次遍历或称广度优先搜索)

在#把二叉树打印成多行#的基础上修改一下,加一个count计数器计算层数。 https://blog.nowcoder.net/n/b60136bbfaf345c4b498cc71705b77ac

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pRoot TreeNode类 
# @return int整型
#
class Solution:
    def TreeDepth(self , pRoot: TreeNode) -> int:
        if pRoot==None:
            return 0
        
        count=0
        queue=[]
        queue.insert(0,pRoot)
        while len(queue)>0:
            #row=[]
            for i in range(len(queue)):#目前队列的长度,就是每层节点的个数                
                node=queue.pop()#出队,访问
                #row.append(node.val)
                if node.left:
                    queue.insert(0,node.left)
                if node.right:
                    queue.insert(0,node.right)
            count=count+1
            
        return count

法二:递归方法

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pRoot TreeNode类 
# @return int整型
#
class Solution:
    def TreeDepth(self , pRoot: TreeNode) -> int:
        if pRoot==None:
            return 0
        else:
            return max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))+1
全部评论

相关推荐

点赞 评论 收藏
分享
zyNotCute:感觉问题主要在学校,以及项目吧,项目有些偏简单了;专业技能方面没写redis和微服务有一点小薄弱;当然acm打得好也是不错的。可以再打磨一下祝找工顺利
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务