Search code examples
python-3.xalgorithmiterationbinary-search-treetraversal

How to call class from another class in python


I am pretty new and trying to work on an algorithm challenge (Binary Inorder Traversal). I am trying to go through a tree (iterative) but for some reason there is a disconnect when I call the function.

from typing import List
from typing import Optional

# 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 inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        res = []
        stack = []
        cur = root
        while cur or stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            res.append(cur.val)
            cur = cur.right
        print(res)

Solution.inorderTraversal(Solution,[1,'',2,3])

I get "list object has no attribute 'left error and also note that the second value in the root is supposed to be 'null' but when I use 'null' it says null is not defined.


Solution

  • Some things to consider:

    • Your classes are what you would typically expect in a LeetCode challenge. LeetCode will convert a JSON-like text input for you into a TreeNode instance and will then call your method with that as argument.

    • The description of such code challenges is most often language agnostic, so there will be mention of null, when in an actual programming language this will be None (Python), NULL (c), ...etc. This is something to take into account.

    • The function you need to implement is supposed to return the result. Printing it is not enough and not needed

    When you want to call your function yourself, you cannot just pass a list as argument, you need to pass a TreeNode instance. For instance, like this:

    # This is what LeetCode will do with "[1, null, 2, 3]"
    root = TreeNode(1, None, TreeNode(2, TreeNode(3)))
    result = Solution().inorderTraversal(root)
    print(result)
    

    If you want to dynamically build that TreeNode from a list, you can for instance use a function like provided here.