-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathInvert Binary Tree.py
More file actions
71 lines (57 loc) · 1.68 KB
/
Invert Binary Tree.py
File metadata and controls
71 lines (57 loc) · 1.68 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
Invert Binary Tree
Write a function that takes in a Binary Tree and inverts it.In other words,the function
should swap every left node in the tree for its corresponding right node.
Each BinaryTree node has an integer value, a left child node, and a right child node.
Children nodes can either be BinaryTree nodes themselves or None/null.
Sample Input
tree = 1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Sample Output
tree = 1
/ \
3 2
/ \ / \
7 6 5 4
/ \
9 8
"""
# SOLUTION 1
# Recursive
# O(n) time | O(d) space where d is longest depth of a branch
def invertBinaryTree(tree):
if tree is None:
return
if tree:
tree.left, tree.right = tree.right, tree.left
invertBinaryTree(tree.left)
invertBinaryTree(tree.right)
# This is the class of the input binary tree.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# SOLUTION 2
# Iterative
# O(n) time | O(n)
def invertBinaryTree(tree):
queue = [tree]
while len(queue):
current = queue.pop(0)
if current is None:
continue
current.left, current.right = current.right, current.left
queue.append(current.left)
queue.append(current.right)
# This is the class of the input binary tree.
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None