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

Tree exercise issue

I am trying to test this code using VScode, but I guess im declaring something wrong.

Could you please support me guys??

Thanks a lot!!!

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

# 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 invertTree(self,root):
        if not root:
            return None
        
        # swap the children
        tmp = root.left       <----- here shows me the issue
        root.left = root.right
        root.right = tmp
        
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

tree = Solution()
node1 = TreeNode("4","2","7")
node2 = TreeNode("2","1","3")
node3 = TreeNode("7","6","9")
tree.invertTree(node1)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-8dc5914e9836> in <module>()
     23 node2 = TreeNode("2","1","3")
     24 node3 = TreeNode("7","6","9")
---> 25 tree.invertTree(node1)

1 frames
<ipython-input-13-8dc5914e9836> in invertTree(self, root)
     11 
     12         # swap the children
---> 13         tmp = root.left
     14         root.left = root.right
     15         root.right = tmp

AttributeError: 'str' object has no attribute 'left'

this is the error I get, I guess the issue is during the creation of the nodes but I have no clue how to do it.

>Solution :

Your lefts and rights are just strings (that don’t have left and right attributes, as the error message that you probably get says).

You need to pass TreeNodes instead, e.x.:

tree = Solution()
root = TreeNode(
    "4",
    TreeNode(
        "2",
        TreeNode("1"),
        TreeNode("3")
    ),
    TreeNode(
        "7",
        TreeNode("6"),
        TreeNode("9")
    )
)
tree.invertTree(root)
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