-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvert_binary_tree.py
More file actions
37 lines (26 loc) · 921 Bytes
/
invert_binary_tree.py
File metadata and controls
37 lines (26 loc) · 921 Bytes
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
32
33
34
35
36
37
# 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):
if root is None:
return root
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
# Time Complexity: O(n) where n is the number of nodes
# Space Complexity: O(h) where h is the height of tree
def invertTree(self, root):
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
stack.append(node.right) if node.right else None
stack.append(node.left) if node.left else None
return root