Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Leetcode problem 100, understanding TreeNode

I didn’t know where to post this question, but stackoverflow has been helpful before, so I am going to post my question here.

This question is related to Leetcode problem number 100 (Same Tree) and my question is "how do TreeNode" actually work?

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

The first test case of the problem has two trees:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

q = [1,2,3]
p = [1,2,3]

You’re supposed to return True if the trees are the same and False otherwise.

I would have thought this would’ve solved that specific test case:

return q.val == p.val and q.left == p.left and q.right == p.right

but instead of getting output True, I get False??

For science I tried just return q.val, expecting the output to be 1, but instead I got output True?

I simply don’t understand how these trees work. I’ve also tried defining the class TreeNode in a Jupyter Notebook and defined two trees:

q = TreeNode()
q.val = 1
q.left = 2
q.right = 3

I did the same for p and ran:

q.val == p.val and q.left == p.left and q.right == p.right

which did output True.

What am I missing? What is it, that I am not understanding?

>Solution :

A tree node has a value and two children nodes (Left and Right). Left references the node to the ‘Left’, and right references the node to the ‘Right’.

If these Trees were created separately than the left and right children would be different objects and therefore they are not the same. The comparison should look like:

q.val == p.val and q.left.val == p.left.val and q.right.val == p.right.val

Also, in the case of returning True instead of 1, you should post your code. If you are returning directly to LeetCode, then LeetCode is probably expecting a Boolean value to be returned, which means a 1 will be interpreted as True.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading