[SOLVED] Binary Tree Transversing


I’m really new to coding and was stuck at one of the Leetcode problems on Binary Tree Transversing.

Can anyone please explain what the following line of code means:

def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:

From what I understood, the core was trying to define a function pre-order traversal and a class TreeNode was defined earlier. However I was not able to get what root: Optional[TreeNode] and ->List[int] meant.

Thanks in advance


If it helps, you can ignore the type hints in that function declaration. If you change it to this, it will still work:

def preorderTraversal(self, root):

The type hints are helping editors (and you) to know the expected type of parameters and of the function’s return value:

  • Optional: this means the value could be None
  • TreeNode: this means the value is an instance of the class TreeNode. LeetCode provides its definition in a comment block in the original code template you get to work with. It is indeed predefined.
  • List[int]: this means the returned value should be a list, and the list elements should be integers.

Answered By – trincot

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *