go: add «1110. Delete Nodes And Return Forest»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
33e47203c6
commit
c70aba338e
1 changed files with 38 additions and 0 deletions
38
go/delete-nodes-and-return-forest.go
Normal file
38
go/delete-nodes-and-return-forest.go
Normal file
|
@ -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
|
||||
}
|
Loading…
Reference in a new issue