226. Invert Binary Tree
[Easy] “Invert a Binary Tree."
Note: old solution, should review (TODO:
)
Python3:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
resTree = root
if not root:
return root
# if either side exists, swap
if resTree.left or resTree.right:
tempNode = root.left
resTree.left = resTree.right
resTree.right = tempNode
# swap next level
if resTree.left:
tempInvertLeft = self.invertTree(resTree.left)
resTree.left = tempInvertLeft
if resTree.right:
tempInvertRight = self.invertTree(resTree.right)
resTree.right = tempInvertRight
return resTree