1. 程式人生 > >LeetCode刷題-——Maximum Depth of Binary Tree(二叉樹的最大深度)

LeetCode刷題-——Maximum Depth of Binary Tree(二叉樹的最大深度)

連結:

點選開啟連結

題目:

給定一個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

Example:

給定二叉樹 [3,9,20,null,null,15,7]
    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

解析:

  • 如果根節點為空,則深度為0,返回0,遞迴的出口
  • 如果根節點不為空,那麼深度至少為1,然後我們求他們左右子樹的深度
  • 比較左右子樹深度值,返回較大的那一個
  • 通過遞迴呼叫

解答:

# 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 root == None:
            return 0
        else:
            left = 1
            right = 1
            left = left + self.maxDepth(root.left)
            right = right + self.maxDepth(root.right)
            
            return max(left,right)
        

簡潔版:

# 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 root == None:
            return 0
        else:
            return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1