Skip to content

Instantly share code, notes, and snippets.

@agadelshin
Created June 27, 2021 09:14
Show Gist options
  • Save agadelshin/35f9cf5ad1fbec75388caf890b8d100c to your computer and use it in GitHub Desktop.
Save agadelshin/35f9cf5ad1fbec75388caf890b8d100c to your computer and use it in GitHub Desktop.
Merge trees in golang
package main
import "fmt"
type Node struct {
Name string
Type string
children []*Node
}
func mergeNodes(t1 []*Node, t2 []*Node) []*Node {
for id2, node2 := range t2 {
if id, found := findNode(t1, node2); found {
newNode := &Node{
Name: node2.Name,
Type: node2.Type,
children: mergeNodes(t1[id].children, node2.children),
}
newt2 := append(t2[:id2], t2[id2+1:]...)
newt1 := append(t1[:id], t1[id+1:]...)
return append(append(newt2, newt1...), newNode)
}
}
return append(t1, t2...)
}
func findNode(t1 []*Node, node *Node) (int, bool) {
for i, node1 := range t1 {
if node1.Name == node.Name {
return i, true
}
}
return -1, false
}
func printChanges(root *Node) {
for _, s := range root.children {
fmt.Println(s.Name)
for _, e := range s.children {
fmt.Println(" ", e.Name)
for _, c := range e.children {
fmt.Println(" ", c.Name)
for _, i := range c.children {
fmt.Printf(" %s ", i.Name)
}
fmt.Println()
}
}
}
}
func main() {
root := &Node{
Name: "root",
Type: "root",
children: nil,
}
node1sub1sub1 := &Node{
Name: "mysql",
Type: "component",
children: nil,
}
node1sub2sub1 := &Node{
Name: "postgresql",
Type: "component",
children: nil,
}
node1sub2 := &Node{
Name: "azure",
Type: "environment",
children: []*Node{node1sub2sub1},
}
node1sub1 := &Node{
Name: "azure",
Type: "environment",
children: []*Node{node1sub1sub1},
}
node1 := &Node{
Name: "dev",
Type: "stage",
children: []*Node{node1sub1},
}
node2sub1sub1 := &Node{
Name: "mysql",
Type: "component",
children: nil,
}
node2sub1 := &Node{
Name: "test",
Type: "environment",
children: []*Node{node2sub1sub1},
}
node2 := &Node{
Name: "dev",
Type: "stage",
children: []*Node{node2sub1, node1sub2},
}
root.children = mergeNodes(root.children, []*Node{node1})
root.children = mergeNodes(root.children, []*Node{node2})
printChanges(root)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment