Skip to content

Commit

Permalink
feature: invert binary tree revisit
Browse files Browse the repository at this point in the history
  • Loading branch information
solairerove committed Jan 3, 2024
1 parent 0ed7cb5 commit dd82fb8
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions trees/InvertBinaryTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,17 @@ def invert_tree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# O(n) time || O(h) space
def invert_tree_stack(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
return root

stack = [root]
while stack:
curr = stack.pop()
curr.left, curr.right = curr.right, curr.left
node = stack.pop()
node.left, node.right = node.right, node.left

if curr.left:
stack.append(curr.left)
if node.left:
stack.append(node.left)

if curr.right:
stack.append(curr.right)
if node.right:
stack.append(node.right)

return root

0 comments on commit dd82fb8

Please sign in to comment.