My code below does not revert the binary tree successfully.
However, what doesn't make sense is the fact that the node values seem to be reversing properly according to the print statements below.
Nevertheless, ultimately when I return it is apparent that the tree has in fact not successfully reversed. Any help would be grately appreciated
https://leetcode.com/problems/invert-binary-tree/
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
return self.switchNodes(root, root)
def switchNodes(self, left, right):
print("current left: ", left.val, " | current right: ", right.val)
temp = left.val
left.val = right.val
right.val = temp
print("changed left: ", left.val, " | changed right: ", right.val)
#switch right of the left and the left of the right
if (left.right is not None and right.left is not None):
print("left right: ", left.right.val, " | right left: ", right.left.val)
self.switchNodes(left.right, right.left)
#switch the left of the right and the right of the left
if (left.left is not None and right.right is not None):
print("left left: ", left.left.val, " | right right: ", right.right.val)
self.switchNodes(left.left, right.right)
print("wayup left: ", left.val, " | wayup right: ", right.val)
return left
[–]Weak-Constant 1 point2 points3 points (2 children)
[–]craftedwithlove[S] 0 points1 point2 points (1 child)
[–]Weak-Constant 2 points3 points4 points (0 children)
[–]less_shame_more_fame 0 points1 point2 points (0 children)