tree.go 933 字节
package domain

const (
	StructTree = "tree"
	StructList = "list"
)

type TreeNode interface {
	PID() string
	ID() string
}

type Tree struct {
	Node  TreeNode `json:"node"`
	Nodes []*Tree  `json:"nodes"`
}

func traverse(tree *Tree, node TreeNode) bool {
	list := tree.Nodes
	var match bool = false
	for i := range list {
		id, pid := list[i].Node.ID(), node.PID() //list[i].Node.PID() == node.ID()
		if pid == id {
			list[i].Nodes = append(list[i].Nodes, NewTree(node))
			return true
		}
		if match || traverse(list[i], node) {
			match = true
			break
		}
	}
	return match
}

func NewTrees(nodes []TreeNode) *Tree {
	var tree = &Tree{
		Node:  nil,
		Nodes: make([]*Tree, 0),
	}
	for i := range nodes {
		match := traverse(tree, nodes[i])
		if !match {
			tree.Nodes = append(tree.Nodes, NewTree(nodes[i]))
		}
	}
	return tree
}

func NewTree(node TreeNode) *Tree {
	return &Tree{
		Node:  node,
		Nodes: make([]*Tree, 0),
	}
}