|
|
|
|
|
by TheLoneWolfling
4020 days ago
|
|
Better solution: def invertTree(self, root):
queue = []
if root is not None:
queue.append(root)
while current is not None or len(queue) > 0:
while current is None:
current = queue.pop()
current.left, current.right = current.right, current.left
if current.left is not None:
if current.right is not None:
queue.append(current.right)
current = current.left
else:
current = current.right
return root
No needless enqueuing / dequeuing of things unless you need to. As a bonus, if the nodes maintain a count of how many children the have overall you can always recurse on the smaller child first and use less memory. |
|