Let’s say that you have a binary tree and we needed to know it’s maximum depth.
Binary tree input data
[3,9,20,null,null,15,7] could be visualised as follows:
In the above example, the depth would be 3. As there are 3 levels.
How would we write some Python code to work this out?
As usual, a TreeNode is defined as follows:
As we need to loop through the same data types, this would be a perfect time to practice some recursion!
What we have done here, is
return 0 if a node is empty, or doesn’t exist. Then we attempt to get the depth of both it’s left and right children.
At this point, we increment whichever is found and return that.
If you’re interested, you can practice this exercise on Leetcode over here: https://leetcode.com/problems/maximum-depth-of-binary-tree/