-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1660 v1.py
49 lines (38 loc) · 1.51 KB
/
m1660 v1.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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def correctBinaryTree(self, root: TreeNode) -> TreeNode:
toVisit = [(root, 0)] # (curr, depth)
depths = {}
while toVisit :
curr, depth = toVisit.pop()
if not curr :
continue
if curr in depths and depths[curr] < depth :
continue
depths[curr] = depth
depth += 1
toVisit.append((curr.left, depth))
toVisit.append((curr.right, depth))
toVisit.append((root))
while toVisit :
parent = toVisit.pop()
if parent.left and \
((parent.left.left and depths[parent.left] == depths[parent.left.left]) or \
(parent.left.right and depths[parent.left] == depths[parent.left.right])) :
parent.left = None
break
if parent.right and \
((parent.right.right and depths[parent.right] == depths[parent.right.right]) or \
(parent.right.left and depths[parent.right] == depths[parent.right.left])) :
parent.right = None
break
if parent.right :
toVisit.append(parent.right)
if parent.left :
toVisit.append(parent.left)
return root