dave on Nostr: ```go type Tree struct { val int left *Tree right *Tree } func ArrToTree(arr []int) ...
```go
type Tree struct {
val int
left *Tree
right *Tree
}
func ArrToTree(arr []int) *Tree {
// 创建根节点
root := &Tree{}
// 节点队列
nodeQueue := []*Tree{}
// 入队
nodeQueue = append(nodeQueue, root)
// 当前节点索引
index := 0
// 处理节点
for len(nodeQueue) > 0 && index < len(arr) {
// 取出节点
node := nodeQueue[0]
nodeQueue = nodeQueue[1:]
// 节点赋值
node.val = arr[index]
// 左右节点入队
if (2*index + 1) < len(arr) {
leftNode := &Tree{}
node.left = leftNode
nodeQueue = append(nodeQueue, leftNode)
}
if (2*index + 2) < len(arr) {
rightNode := &Tree{}
node.right = rightNode
nodeQueue = append(nodeQueue, rightNode)
}
// 下一个节点
index++
}
return root
}
```
Published at
2023-02-10 07:56:58Event JSON
{
"id": "1e1c1e6c69543b3d82d9788cf0758fb63ca4fc71c9257037c01b0e72efe1d50d",
"pubkey": "5c10ed0678805156d39ef1ef6d46110fe1e7e590ae04986ccf48ba1299cb53e2",
"created_at": 1676015818,
"kind": 1,
"tags": [
[
"e",
"4484ea7170574e8d2e9463b492c03c9f796c6788d2601f96e5ecebe6b8ec85a4",
"",
"reply"
],
[
"p",
"f9f75277cbffa1bd3c53d33b11c32e74a18ae0dddac6d00f801f165f262bca20"
]
],
"content": "```go\ntype Tree struct {\n\tval int\n left *Tree\n right *Tree\n}\n\n\nfunc ArrToTree(arr []int) *Tree {\n\t// 创建根节点\n\troot := \u0026Tree{}\n\t// 节点队列\n\tnodeQueue := []*Tree{}\n\t// 入队\n\tnodeQueue = append(nodeQueue, root)\n\t// 当前节点索引\n\tindex := 0\n\t// 处理节点\n\tfor len(nodeQueue) \u003e 0 \u0026\u0026 index \u003c len(arr) {\n\t\t// 取出节点\n\t\tnode := nodeQueue[0]\n\t\tnodeQueue = nodeQueue[1:]\n\t\t// 节点赋值\n\t\tnode.val = arr[index]\n\t\t// 左右节点入队\n\t\tif (2*index + 1) \u003c len(arr) {\n\t\t\tleftNode := \u0026Tree{}\n node.left = leftNode\n\t\t\tnodeQueue = append(nodeQueue, leftNode)\n\t\t}\n\t\tif (2*index + 2) \u003c len(arr) {\n\t\t\trightNode := \u0026Tree{}\n\t\t\tnode.right = rightNode\n\t\t\tnodeQueue = append(nodeQueue, rightNode)\n\t\t}\n // 下一个节点\n\t\tindex++\n\t}\n\treturn root\n}\n```",
"sig": "5a8cb31f7437f894689d29acea1ef48f3eeee1f98ad1429737061766c3c958679798477c22441b53f8d0a8c3a801382b80dacdc8739c2e0ce0bedee79a02bbaa"
}