二叉树最大深度递归的图形解释

二叉树最大深度递归的图形解释_第1张图片

import collections


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def nums_to_tree(nums):
    if not nums:
        return []

    queue = collections.deque()
    root = TreeNode(nums[0])
    queue.append(root)
    i = 1
    while i < len(nums):
        node = queue.popleft()
        if i < len(nums) and nums[i] != -1:
            node.left = TreeNode(nums[i])
            queue.append(node.left)
        i += 1
        if i < len(nums) and nums[i] != -1:
            node.right = TreeNode(nums[i])
            queue.append(node.right)
        i += 1
    return root


class Solution:
    def maxDepth(self, root):
        # 节点为空,高度为 0
        if root == None:
            return 0

        # 递归计算左子树的最大深度
        leftHeight = self.maxDepth(root.left)
        # 递归计算右子树的最大深度
        rightHeight = self.maxDepth(root.right)

        # 二叉树的最大深度 = 子树的最大深度 + 1(1 是根节点)
        return max(leftHeight, rightHeight) + 1


# 输入为 3 9 20 null null 15 7
#      3
#    /   \
#   9    20
#       /  \
#      15   7

nums = [3, 9, 20, 'null', 'null', 15, 7]
nums = [int(i) if i != 'null' else -1 for i in nums]
root = nums_to_tree(nums)
print(Solution().maxDepth(root))

你可能感兴趣的:(算法,力扣,python,数据结构,算法)