package main
import (
"fmt"
)
type TreeNode struct {
data int
left*TreeNode
right*TreeNode
}
func CreateTree(data []int) []TreeNode {
treeNodes := make([]TreeNode, 0)
for i, data := range data {
treeNodes= append(treeNodes, TreeNode{})
treeNodes[i].data=data
}
for i:=0;i<len(treeNodes)/2 ;i++{
treeNodes[i].left=&treeNodes[2*i+1]
if i*2+2<len(treeNodes) {
treeNodes[i].right=&treeNodes[2*i+2]
}
}
fmt.Println(treeNodes)
return treeNodes
}
func PreOrder(ts *TreeNode) {
if ts==nil {
return
}
PreOrder(ts.left)
PreOrder(ts.right)
fmt.Println(ts.data)
}
func count(t *TreeNode) int {
if t==nil {
return 0
}
return 1+count(t.left)+count(t.right)
}
func main() {
data:=[]int{3,2,4,23,12,34,54,17,18,21,28}
tree := CreateTree(data)
fmt.Println(count(&tree[0]))
}
golang求出节点总数
最新推荐文章于 2024-04-19 14:07:43 发布