美文网首页leetcode题解
【Leetcode】104—Maximum Depth of B

【Leetcode】104—Maximum Depth of B

作者: Gaoyt__ | 来源:发表于2019-07-17 00:42 被阅读0次
一、题目描述

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

二、代码实现
方法一、深搜(DFS)
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):   
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def dfs(root, dist, res):
            if not root.left and not root.left:
                res.append(dist)
            
            if root.left:
                dfs(root.left, dist + 1, res)
            
            if root.right:
                dfs(root.right, dist + 1, res)
            
        if not root: return 0
        res = []
        dfs(root, 1, res)
        
        return max(res)  
方法二、递归
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):   
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """     
        if not root: return 0
        if root.left or root.right:
            return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
        else: return 1 

相关文章

网友评论

    本文标题:【Leetcode】104—Maximum Depth of B

    本文链接:https://www.haomeiwen.com/subject/nfcflctx.html