发动态

没有新消息

更多内容

#福大大架构师每日一题#2023-10-04:用go语言,现有一棵无向、无根的树,树中有 n 个节点,按从 0 到 n

智小Q AI个人助理

从你的问题中,我推断出你需要用Go语言编写一个程序来处理一棵无向树的节点价格问题。首先,我们需要构建一个树的数据结构,然后我们可以计算每个节点的总价格。 以下是一个可能的解决方案: ```go package main import "fmt" type Node struct { ID int Price int Children []*Node } func constructTree(n int, edges [][]int, price []int) *Node { if n <= 0 { return nil } nodes := make([]*Node, n) for i := 0; i < n; i++ { nodes[i] = &Node{ID: i, Price: price[i]} } for _, edge := range edges { a, b := edge[0], edge[1] nodes[a].Children = append(nodes[a].Children, nodes[b]) nodes[b].Children = append(nodes[b].Children, nodes[a]) } return nodes[0] } func calculateTotalPrice(node *Node) int { if node == nil { return 0 } total := node.Price for _, child := range node.Children { total += calculateTotalPrice(child) } return total } func main() { n := 6 edges := [][]int{{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}} price := []int{4, 2, 1, 3, 6, 5} root := constructTree(n, edges, price) totalPrice := calculateTotalPrice(root) fmt.Println("Total price:", totalPrice) } ``` 在这个程序中,我首先定义了一个 Node 结构,它包含节点的 ID、价格以及子节点。接着,我创建了一个构造树函数 constructTree,它接收节点数量、边数组以及价格数组,然后构建出树并返回根节点。在构建过程中,我遍历边数组,为每对相邻节点创建一条双向边。最后,我定义了一个计算总价格的函数 calculateTotalPrice,它遍历树并累计每个节点的价格。主函数中,我创建了一个示例树并打印出总价格。

13 赞+1
0
评论

0 条评论

暂无评论,快来写下您的评论

正在发声