104. Maximum Depth of Binary Tree(二叉树深度-DFS方法)

1,125次阅读
没有评论
Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

解法
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    #深度优先
    def _dfs(self, node, max_level):
        
        #如果当前节点的左右节点都不存在,则直接返回
        if not node.left and not node.right: 
            return max_level
        #节点都存在的时候需要继续递归求解
        elif node.left and node.right:
            return max(self._dfs(node.left,max_level+1),self._dfs(node.right,max_level+1))
        #只存在左节点
        elif node.left:
            return self._dfs(node.left,max_level+1)
        #只存在右节点
        else:
            return self._dfs(node.right,max_level+1)
    def maxDepth(self, root: TreeNode) -> int:
        
        #深度优先
        if not root: 
            return 0
        max_level = self._dfs(root,1)
        return max_level
        

补上一张图解析

104. Maximum

admin
版权声明:本站原创文章,由admin2019-03-25发表,共计804字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)