Skip to content

Commit d3d2595

Browse files
committed
Solution to 1110
1 parent 3df0bea commit d3d2595

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

src/unresolved/1110.delete-nodes-and-return-forest.jl renamed to src/problems/1110.delete-nodes-and-return-forest.jl

+28-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
# ---
22
# title: 1110. Delete Nodes And Return Forest
33
# id: problem1110
4-
# author: Tian Jun
5-
# date: 2020-10-31
4+
# author: Indigo
5+
# date: 2022-03-19
66
# difficulty: Medium
77
# categories: Tree, Depth-first Search
88
# link: <https://leetcode.com/problems/delete-nodes-and-return-forest/description/>
@@ -43,5 +43,30 @@
4343
## @lc code=start
4444
using LeetCode
4545

46-
## add your code here:
46+
function del_nodes1110(node::TreeNode{Int}, to_delete::Vector{Int})
47+
to_deletes = Set(to_delete)
48+
res = TreeNode{Int}[]
49+
queue = [(node, true)]
50+
51+
while !isempty(queue)
52+
root, flg = popfirst!(queue)
53+
if root.val to_deletes
54+
!isnothing(root.left) && push!(queue, (root.left))
55+
!isnothing(root.right) && push!(queue, (root.right))
56+
continue
57+
end
58+
for child in (:left, :right)
59+
isnothing(getproperty(root, child)) && continue
60+
if getproperty(root, child).val to_deletes
61+
!isnothing(getproperty(root, child).left) && push!(queue, (getproperty(root, child).left, true))
62+
!isnothing(getproperty(root, child).right) && push!(queue, (getproperty(root, child).right, true))
63+
setproperty!(root, child, nothing)
64+
else
65+
push!(queue, (getproperty(root, child), false))
66+
end
67+
end
68+
flg && push!(res, root)
69+
end
70+
res
71+
end
4772
## @lc code=end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
@testset "1110.delete-nodes-and-return-forest.jl" begin
2+
@test del_nodes1110(TreeNode{Int}([1, 2, 3, 4, 5, 6, 7]), [3, 5]) == [TreeNode{Int}([1, 2, nothing, 4]), TreeNode(6), TreeNode(7)]
3+
end

0 commit comments

Comments
 (0)