2

I am working through some problems on leetcode and i dont understand the same code that they have written. For example, why is there an arrow pointing to int ( -> int:)? Also i dont understand what the TreeNode is being used for. Is it just to validate the inputs?

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:
VickTree
  • 889
  • 11
  • 26

1 Answers1

2

Called function annotations, have a read of this page.

https://www.python.org/dev/peps/pep-3107/

or

What does -> mean in Python function definitions?

In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.

There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.

user: Katriel

The TreeNode itself is part of the data structure of a binary tree, I do not know the specific leetcode question being mentioned but essentially the tree is made up of many TreeNodes that reference other TreeNodes through the variables self.left and left.right, the names are used to emulate what a visual binary tree would traditionally look like. They are just defining the Node so that you can understand what class to expect in answering the question.

https://www.geeksforgeeks.org/binary-tree-data-structure/

Chrismon Chin
  • 429
  • 2
  • 12