LC104:
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Input: root = [3,9,20,null,null,15,7]
Output: 3
Input: root = [1,null,2]
Output: 2
1
/ \
n 2
From root, find length of right and left subtree recusrively: Pick the max and add 1
1
/ \
2 3
/ \
4 5
\
6
root = 1
depth(1) = max(depth(2), depth(3)) + 1 = max(1, 3) + 1 = 4 <- max depth
depth(2) = max(0, 0) +1 = 0 + 1 = 1
depth(3) = max(depth(4), depth(5)) + 1 = max(1, 2) + 1 = 3
depth(4) = 0 + 1 = 1
depth(5) = max(0, depth(6)) + 1 = max(0, 1) + 1 = 2
depth(6) = 0 + 1 = 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root == None:
return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
return max(left, right) + 1