104. The maximum depth of a binary tree

Maximum depth of a binary tree


Problem
Given a binary tree, find its maximum depth.
The depth of a binary tree is the number of nodes on the longest path from the root node to the farthest leaf node.
Explanation: A leaf node is a node that has no child nodes.
Example:
Given a binary tree [3,9,20,null,null,15,7],
insert image description here
return its maximum depth of 3.
Source: LeetCode
Link: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
Idea
Using recursion, first traverse the left and right subtrees to find the maximum depth of the left and right subtrees +1 (root node) is the maximum depth of the number. It traverses the left and right nodes of the left and right subtrees repeatedly, and finally returns the maximum depth of the left and right subtrees from the leaf node to the root node.
The Python code is as follows:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        # 节点为空则返回0
        if not root:
        	return 0
        else:
        	return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

Reference link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339458&siteId=291194637