user6308605
user6308605

Reputation: 731

How to run TreeNode locally python

I have a really stupid question that my head can't seem to wrap up. I want to test this locally instead of on leetcode. How do I run this?

# 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(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if root is None:
            return []
        
        stack, output = [root, ], []
        
        while stack:
            root = stack.pop()
            if root is not None:
                output.append(root.val) # Error here
                if root.right is not None:
                    stack.append(root.right)
                if root.left is not None:
                    stack.append(root.left)
        
        return output

My attempt is:

input = [1,None,2,3]

s = Solution()
print(s.preorderTraversal(input))

but I'm getting error:

AttributeError: 'list' object has no attribute 'val'

Upvotes: 1

Views: 781

Answers (1)

trincot
trincot

Reputation: 351039

Some code challenge sites, such as Leet Code, will transform the list input (actually the text input having JSON notation) into an instance of TreeNode, and will pass that as argument to the function with your solution code.

When you want to run the solution locally, you'll have to take care of this transformation yourself. For that purpose you could make use of this function -- specifically for binary trees:

def fromlist(values):
    def create(it):
        value = next(it)
        return None if value is None else TreeNode(value)
        
    if not values:
        return None
    it = iter(values)
    root = TreeNode(next(it))
    nextlevel = [root]
    try:
        while nextlevel:
            level = nextlevel
            nextlevel = []
            for node in level:
                if node:
                    node.left = create(it)
                    node.right = create(it)
                    nextlevel += [node.left, node.right]
        
    except StopIteration:
        return root
    raise ValueError("Invalid list")

For your case, you could call it as follows:

input = [1,None,2,3]
s = Solution()
print(s.preorderTraversal(fromlist(input)))

Upvotes: 3

Related Questions