Question Maximum Depth of Binary Tree in Python ?

Bulldog13

Golden Member
Jul 18, 2002
1,655
1
81
Hello,

I have been studying leet code and am on question 104. Maximum Dept of a Binary Tree.


I am an experienced C# programmer and understand the recursion behind the answer.

I am confused on the Python bit of it, particularly :

Input: root = [3,9,20,null,null,15,7]
Output: 3


It seems like a List [3,9,20,null,null,15,7] is being passed in, but it is somehow being converted to a Treenode class ? Or a list of Treenode classes ?

If [3,9,20,null,null,15,7] is being passed in, where exactly is the conversion to TreeNode taking place ?

I am using Pycharm Community and cannot get it to work locally, only in there online IDE. It barfs on the 'null' type.

If someone could shed some light on how this list is being converted into a tree, it would be appreciated.

Code:
# 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: Optional[TreeNode]) -> int:
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        else:
            left_height = self.maxDepth(root.left)
            right_height = self.maxDepth(root.right)
            return max(left_height, right_height) + 1
 

Bulldog13

Golden Member
Jul 18, 2002
1,655
1
81
Nevermind - the implementation and loading of the tree was hidden from the user. The code to actually populate the tree is below:

Python:
s = Solution()
r = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
print(s.maxDepth(r))