'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!!!

# 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 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yevhen Kuzmovych