-
Notifications
You must be signed in to change notification settings - Fork 3
/
83_Google_Invert_Binary_Search_Tree.py
executable file
·70 lines (51 loc) · 1.33 KB
/
83_Google_Invert_Binary_Search_Tree.py
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
"""
This problem was asked by Google.
Invert a binary tree.
For example, given the following tree:
a
/ \
b c
/ \ /
d e f
should become:
a
/ \
c b
\ / \
f e d
"""
from inspect import getargspec
from itertools import dropwhile
class node:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
# def __repr__(self):
# return "{}->({}, {})".format(self.data, self.left, self.right)
#https: // codereview.stackexchange.com / a / 109410
def __repr__(self):
if self.right is not None:
fmt = '{}({data!r}, {left!r}, {right!r})'
elif self.left is not None:
fmt = '{}({data!r}, {left!r})'
else:
fmt = '{}({data!r})'
return fmt.format(type(self).__name__, **vars(self))
def invert_bst(root: node):
root.left, root.right = root.right, root.left
if root.left:
invert_bst(root.left)
if root.right:
invert_bst(root.right)
return root
if __name__=="__main__":
bst = node('a',
left=node('b',
left=node('d'),
right=node('e')),
right=node('c',
left=node('f')))
print(bst)
inverted_bst = invert_bst(bst)
print(inverted_bst)