invert_binary_tree
1from typing import Optional 2from utils import TreeNode 3 4 5# @leet start 6class Solution: 7 def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 8 """ 9 To invert a binary tree, we want to change every left and right subtree. 10 To do this, we swap them and then iterate through the left and right sutbrees of the root. 11 This is easiest done recursively. 12 """ 13 if not root: 14 return 15 root.left, root.right = root.right, root.left 16 self.invertTree(root.left) 17 self.invertTree(root.right) 18 return root 19 20 21# @leet end 22 23 24def test(): 25 assert 2 + 2 == 4
class
Solution:
7class Solution: 8 def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 9 """ 10 To invert a binary tree, we want to change every left and right subtree. 11 To do this, we swap them and then iterate through the left and right sutbrees of the root. 12 This is easiest done recursively. 13 """ 14 if not root: 15 return 16 root.left, root.right = root.right, root.left 17 self.invertTree(root.left) 18 self.invertTree(root.right) 19 return root
8 def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 9 """ 10 To invert a binary tree, we want to change every left and right subtree. 11 To do this, we swap them and then iterate through the left and right sutbrees of the root. 12 This is easiest done recursively. 13 """ 14 if not root: 15 return 16 root.left, root.right = root.right, root.left 17 self.invertTree(root.left) 18 self.invertTree(root.right) 19 return root
To invert a binary tree, we want to change every left and right subtree. To do this, we swap them and then iterate through the left and right sutbrees of the root. This is easiest done recursively.
def
test():