1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None
def invertTree(root: TreeNode) -> TreeNode: if not root: return root.right, root.left = invertTree(root.left), invertTree(root.right) return root
if __name__ == "__main__": root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3)
def print_tree(root): if root: print(root.val) print(root.left.val) print(root.right.val)
print_tree(root) print("\n")
root = invertTree(root) print_tree(root)
|