Skip to content

Commit a4d6bcf

Browse files
authored
Create h2458.py asdfkljdasfkljdasklfjdaslf
1 parent 4cff5d9 commit a4d6bcf

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

my-submissions/h2458.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:
9+
def get_heights(curr: Optional[TreeNode],
10+
heights: dict) -> int :
11+
if not curr :
12+
return -1
13+
14+
heights[curr] = 1 + max(get_heights(curr.left, heights),
15+
get_heights(curr.right, heights))
16+
return heights[curr]
17+
18+
def set_del_heights(curr: Optional[TreeNode],
19+
heights: dict,
20+
del_heights: dict,
21+
depth: int = 0,
22+
alt_path_height: int = -1,
23+
parent: Optional[TreeNode] = None) -> None :
24+
if not curr :
25+
return
26+
# is on _the_ or _a_ main branch causing the original root height
27+
if heights[root] - heights[curr] == depth :
28+
# root
29+
if not parent :
30+
del_heights[curr.val] = -1
31+
# one child
32+
elif not parent.left or not parent.right :
33+
del_heights[curr.val] = max(depth - 1, del_heights[parent.val])
34+
# two children
35+
else :
36+
del_heights[curr.val] = max(
37+
depth + heights[parent.right if parent.left == curr else parent.left],
38+
alt_path_height,
39+
del_heights[parent.val])
40+
# non-primary path
41+
else :
42+
del_heights[curr.val] = heights[root]
43+
44+
# left
45+
set_del_heights(curr.left,
46+
heights,
47+
del_heights,
48+
depth + 1,
49+
max(heights[curr.right] + depth + 1 if curr.right else 0,
50+
alt_path_height),
51+
curr)
52+
# right
53+
set_del_heights(curr.right,
54+
heights,
55+
del_heights,
56+
depth + 1,
57+
max(heights[curr.left] + depth + 1 if curr.left else 0,
58+
alt_path_height),
59+
curr)
60+
61+
heights = {}
62+
get_heights(root, heights)
63+
64+
del_heights = {}
65+
set_del_heights(root, heights, del_heights)
66+
67+
return [del_heights[q] for q in queries]

0 commit comments

Comments
 (0)