This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions
1. Title Description
Given a binary tree, find its maximum depth. The depth of a binary tree is the number of nodes along the longest path from the root node to the farthest leaf node.
Note: Leaf nodes are nodes that have no child nodes.
Example:
Given a binary tree [3,9,20,null,null,15,7],
Returns its maximum depth of 3.
Second, train of thought analysis
1. Total tree depth = Max (left subtree depth, right subtree depth) + layer depth of the current node.
2. Left subtree depth = Max (left subtree depth, right subtree depth of left subtree) + layer depth of the current node.
3. Right subtree depth = Max (left subtree depth of right subtree, right subtree depth of right subtree) + layer depth of the current node.
4. Recurse until the node is null.
AC code
class Solution:
def maxDepth(self.root: TreeNode) - >int:
if not root:
return 0
l = self.maxDepth(root.left)
r = self.maxDepth(root.right)
return max(l,r) + 1
Copy the code
The output is:
Four,
This problem is a depth-first search (DFS) implementation code problem. From this problem experience, the theory is very simple, ideas need to open.