老卫带你学---剑指offer刷题系列(38.二叉树的深度)

38.二叉树的深度

问题:

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

解决:

思想:

这道题我们只需要使用队列,保存每次访问的节点以及它的层数信息,最终将深度打印出来即可。这里注意是每一次循环中加1,所以要先让deep=layer,然后再+1.

python代码

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if not pRoot:
            return 0
        nleft=self.TreeDepth(pRoot.left)
        nright=self.TreeDepth(pRoot.right)    
        return max(nleft+1,nright+1)
发布了160 篇原创文章 · 获赞 30 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/yixieling4397/article/details/105024610