forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcorrect-a-binary-tree.py
More file actions
30 lines (27 loc) · 808 Bytes
/
correct-a-binary-tree.py
File metadata and controls
30 lines (27 loc) · 808 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
# Time: O(n)
# Space: O(w)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
pass
class Solution(object):
def correctBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
q = {root:None}
while q:
new_q = {}
for node, parent in q.iteritems():
if node.right in q:
if parent.left == node:
parent.left = None
else:
parent.right = None
return root
if node.left:
new_q[node.left] = node
if node.right:
new_q[node.right] = node
q = new_q