剑指offer 38. 二叉树的深度

原题

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

Reference Answer

思路分析

想轻松一些,直接广度优先搜索,代码如下:

# -*- 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
        self.res = []
        path = [pRoot.val]
        self.dfs(pRoot, path)
        return max(self.res)
    
    def dfs(self, root, path):
        if not root.left and not root.right:
            self.res.append(len(path))
        if root.left:
            self.dfs(root.left, path+[root.left.val])
        if root.right:
            self.dfs(root.right, path+[root.right.val])
            

进阶版本:
由于题中已经明确是二叉树,直接针对二叉树进行深度查询,可以进一步提升效率。

# -*- 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     
        lleft = self.findDepth(pRoot.left)
        lright = self.findDepth(pRoot.right)
        return max(lleft, lright)+1
   
    def findDepth(self, root):
        if not root:
            return 0
        length_left = self.findDepth(root.left)
        length_right = self.findDepth(root.right)
        return max(length_left, length_right) + 1
        

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84310357