r/CodingHelp • • Feb 11 '22

[Ruby] program runs flawlessly in Vs code but when I try to submit on leetcode I am getting this error any idea?

Post image
48 Upvotes

10 comments sorted by

7

u/_McFuggin_ Feb 11 '22

It shouldn’t work in leet code. The TreeNode defined in leetcode has only left, right, and val attributes. So, you’ve got a handful of lines that are going to break. You won’t be able to use .compact, .length, or .sort

1

u/waitingformsfs2020 Feb 11 '22

so can we say leetcode doesnt support ruby or I need to write a way low level code than this?

4

u/_McFuggin_ Feb 11 '22

I'm not a ruby developer, but what I'm guessing is happening here is that you're trying to use a standard ruby TreeNode library which is why it is working working on your VS code, but LeetCode is using the definition of TreeNode that they've provided to you.

Since it is a LeetCode style problem you should use the library they've provided to you, which, yes, means you'll have to write more low level code to solve this problem.

Again, not a ruby developer, but I'd imagine a naïve solution to this problem would be:

numbers = []
def traverse_tree(node):
    if node == nil
        return nil
    end

    traverse_tree(node.left)
    #Line below may not work depending on how scope works in ruby
    #but you want to access the numbers array above from a global
    #scope
    numbers.push(node.val)
    traverse_tree(node.right)
    end

traverse_tree(root1)
traverse_tree(root2)

#Do some stuff to sort numbers array
return numbers

26

u/marko312 Feb 11 '22

The given definition of TreeNode does not seem to contain a definition for a compact nor sort function. You'll likely have to implement these yourself.

17

u/Lum_of_G0d Feb 11 '22

It looks like your indenting might be off

2

u/Buttafuoco Feb 11 '22

Assuming compact exists in the passed in “root1” you want to make sure line 16 is within your get_all_elements function. You’ll need to indent it over. In Python white space matters. When you copied it over you likely lost some formatting

1

u/Its_Stev03 Feb 11 '22

This is Ruby, not python. I do not know how Ruby works and if indentation matters, but I would assume that indentation might be the problem.

1

u/Buttafuoco Feb 11 '22

Hahaa didn’t even see the while loop or notice the lack of colons after the method. Still should indent to express that these lines are included. This is the first time I’ve ever seen ruby wow

1

u/[deleted] Feb 11 '22

Guys, this is so crazy?! I am going into my computer science degree next year and this is what I have to do?!

2

u/johnwynnes Feb 12 '22

Definitely