From c70aba338e3e5526029751624135842d89f28945 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 17 Jul 2024 09:25:50 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB1110.=20Delete=20Nodes=20And?= =?UTF-8?q?=20Return=20Forest=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/delete-nodes-and-return-forest.go | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 go/delete-nodes-and-return-forest.go diff --git a/go/delete-nodes-and-return-forest.go b/go/delete-nodes-and-return-forest.go new file mode 100644 index 0000000..fec92ed --- /dev/null +++ b/go/delete-nodes-and-return-forest.go @@ -0,0 +1,38 @@ +package main + +import "slices" + +func delNodes(root *TreeNode, to_delete []int) []*TreeNode { + var forest []*TreeNode + + var delNodesRec func(*TreeNode) *TreeNode + delNodesRec = func(node *TreeNode) *TreeNode { + if node == nil { + return nil + } + + node.Left = delNodesRec(node.Left) + node.Right = delNodesRec(node.Right) + + if slices.Contains(to_delete, node.Val) { + if node.Left != nil { + forest = append(forest, node.Left) + } + + if node.Right != nil { + forest = append(forest, node.Right) + } + + return nil + } + + return node + } + + root = delNodesRec(root) + if root != nil { + forest = append(forest, root) + } + + return forest +}