pythonbinary-tree

How to run LeetCode answer in local environment


I am working on LeetCode problem 199. Binary Tree Right Side View:

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

I want to debug my code on my IDE (I use Visual Studio Code). It should be possible because I understand the theory behind it, but I don't understand well how this code works properly. Is it possible to debug it locally?

This is the code I am trying to debug:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
    def rightSideView(root):
        res = [ ]
        if not root :
            return res
        queue = [ root ]
        
        while queue :
            
            for n in range(len(queue)) :# 1
                
                first_val = queue.pop(0)
                print("first val",first_val)
                print("n",n)
                
                if n == 0 :
                    res.append(first_val.val)
                    
                if first_val.right :
                    queue.append(first_val.right)
                    
                if first_val.left :
                    queue.append(first_val.left)
        return res

    print(rightSideView([1,2,3,None,5,None,4]))

Solution

  • The LeetCode container will call your function with an argument that is a ListNode instance (or None), not with a list.

    The input that LeetCode works with is text, and the notation used to describe the input is typically JSON-like. The LeetCode framework reads this text and first transforms it to a ListNode instance before calling your function.

    So when you want to test your code outside of that platform, you'll need to do that preprocessing yourself. For instance, if your input is a Python list, then use a function like the following to first convert that list to a tree (ListNode):

    
    def makeTree(lst):
        if not lst:
            return
        values = iter(lst)
        root = TreeNode(next(values))
        queue = [root]
        while queue:
            node = queue.pop(0)
            if node:
                children = [
                    None if value is None else TreeNode(value)
                    for value in (next(values, None), next(values, None))
                ]
                queue.extend(children)
                node.left, node.right = children
    
        return root
    

    Now you can run your test like this:

    print(rightSideView(makeTree([1,2,3,None,5,None,4])))
    

    Note that the code in your question has some indentation issues: the rightSideView function is not supposed to be a method of the TreeNode class. And the final print should not be part of that class either, so both should be unindented one step.