1. 程式人生 > >二叉樹最大深度(遞迴實現python)---LeetCode

二叉樹最大深度(遞迴實現python)---LeetCode

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

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root==None:
            return 0
        leftdpth=self.maxDepth(root.left)
        rightdpth=self.maxDepth(root.right)
        if leftdpth>=rightdpth:
            return leftdpth+1
        else:
            return rightdpth+1

演算法思想:

首先判斷根結點是否存在,然後遞迴呼叫maxDepth,把下一層葉節點當做根節點,每次呼叫都會判斷root是否存在,我們可以這樣理解

leftdepth=self.maxDpeth(root.left.left.left...)

right類似,每次我們都會判斷root左子葉和右子葉是否存在,leftdpth和rightdpth相當於每次遞迴左右子葉的計數器,最後我們取最大的那個加一(加上根結點)

ps:遞迴思想很重要。