Playing Hacks and Stuffs!
We will be given a binary tree and we’re to return the 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.
Let’s take an example on what that means:
First for each subtree in the tree it corresponds to a level
That last level is known as the maximum depth of a binary tree
Now how do we calculate that?
Well if we know the level on the left subtree and the level on the right subtree we can calculate the maximum value of it
Because there might be case where the level of the left subtree might be lower than the right subtree and vice versa
The level of the subtree is also the length of number of elements there
Let’s take this sample with ipython
You can see that when I traverse the left subtree the length of the result is equivalent to it’s level
I can also do that for the right subtree
Now the maximum depth would then be the maximum value between the length returned after traversing the left subarray and the length returned after traversing the right subarray
With recursion we can easily achieve this and what we’ll check will be max(node.left, node.right) + 1
I’m checking the maximum value from traversing the left and array subtree then the result I’ll increment it by 1
That’s because when I do that it would actually start from the node of the parent tree
With that said my solve script is in the link below
Here’s my solve script: link
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + max(Solution.maxDepth(self, root.left), Solution.maxDepth(self, root.right))