-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathinvert_binary_tree.py
More file actions
37 lines (28 loc) · 883 Bytes
/
invert_binary_tree.py
File metadata and controls
37 lines (28 loc) · 883 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
# coding: utf-8
"""
https://leetcode.com/problems/invert-binary-tree/
"""
from collections import deque
class TreeNode: # pragma: no cover
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
new_left = self.invertTree(root.right)
new_right = self.invertTree(root.left)
root.left = new_left
root.right = new_right
return root
class Solution2:
def invertTree(self, root: TreeNode) -> TreeNode:
queue = deque([root, ])
while queue:
node = queue.popleft()
if node:
queue.extend((node.left, node.right))
node.left, node.right = node.right, node.left
return root