LeetCode解题心得——二叉树的最大深度(python)

题目

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

思路

递归 自上而下

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

class Solution:
    def __init__(self):
        self.max_depth = 0
    def maxDepth(self, root: TreeNode, depth=1) -> int:
        if not root:
            return 0
        if (root.left == None) and (root.right == None):
            self.max_depth = max(self.max_depth, depth)
        self.maxDepth(root.left, depth+1)
        self.maxDepth(root.right, depth+1)
        return self.max_depth

递归 自下而上

将求根节点树最大深度的问题转化为求子节点树最大深度的问题

# 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: TreeNode) -> int:
        if not root: return 0
        left_max = self.maxDepth(root.left)
        right_max = self.maxDepth(root.right)
        return max(left_max, right_max) + 1

你可能感兴趣的:(LeetCode)