-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC1325_DeleteLeavesWithGivenValue.py
33 lines (32 loc) · 1.12 KB
/
LC1325_DeleteLeavesWithGivenValue.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
# 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 removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:
stack = [root]
visit = set()
parents = { root : None}
while stack:
node = stack.pop()
if not node.left and not node.right:
if node.val == target:
p = parents[node]
if not p:
return None
if p.left == node:
p.left = None
if p.right == node:
p.right = None
elif node not in visit:
visit.add(node)
stack.append(node)
if node.left:
stack.append(node.left)
parents[node.left] = node
if node.right:
stack.append(node.right)
parents[node.right] = node
return root