-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinvert-binary.py
More file actions
79 lines (63 loc) · 2.02 KB
/
invert-binary.py
File metadata and controls
79 lines (63 loc) · 2.02 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
72
73
74
75
76
77
78
79
# https://leetcode.com/problems/invert-binary-tree/
# convert a binary tree.
#
# 4
# / \
# 2 7
# / \ / \
# 1 3 6 9
# to
# 4
# / \
# 7 2
# / \ / \
# 9 6 3 1
#
# Trivia:
# This problem was inspired by this original tweet by Max Howell:
# Google: 90% of our engineers use the software you wrote (Homebrew),
# but you can’t invert a binary tree on a whiteboard so fuck off.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# The solution to this problem involves using a Queue
# Step1 : Create a Queue with enqueue , dequeue and isempty functionality. These will come handy while
# inverting the binary tree
class Queue():
def __init__(self):
self.items = []
def enqueue(self,key):
self.key = key
self.items.insert(0,key)
def dequeue(self):
return self.items.pop()
def empty(self):
return self.items
def isempty(self):
return len(self.items)==0
def print_q(self):
return self.items
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# Step 2 : if the tree is not an empty tree , enqueue the root into the Queue
# Step 3 : dequeue an element from the Queue , swap its left and right children
# Step 4 : enqueue these children that you just swapped in the Queue , as long as they are not None
# Step 5 : dequeue the next node from the Queue and swap its children .. Keep going.
if root is not None:
my_queue = Queue()
my_queue.enqueue(root)
while not my_queue.isempty():
node = my_queue.dequeue()
node.left , node.right = node.right , node.left
if node.left is not None:
my_queue.enqueue(node.left)
if node.right is not None:
my_queue.enqueue(node.right)
return root