Invert Binary Tree - Solution
Solutions and explanations
Video Explanation
# 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: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# invert then swap
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
Complexity Analysis
- Time Complexity:
O(n)wherenis the number of nodes in the tree. - Space Complexity:
O(h)due to the space used by the recursion stack, wherehis the height of the tree,.
Note: In the worst case, where the tree is skewed, h can be as large as n. In the best case, such as a balanced binary tree, h is O(log n).
# 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: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
# swap the nodes
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
Complexity Analysis
- Time Complexity:
O(n)wherenis the number of nodes in the tree. - Space Complexity:
O(h)due to the space used by the recursion stack, wherehis the height of the tree,.
Note: In the worst case, where the tree is skewed, h can be as large as n. In the best case, such as a balanced binary tree, h is O(log n).