我想用golang实现二叉树前序,请你帮我写一下代码。
时间: 2023-05-23 17:02:05 浏览: 47
Sure, here is the code to implement binary tree pre-order traversal in Golang:
```
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
res := []int{root.Val}
left := preorderTraversal(root.Left)
right := preorderTraversal(root.Right)
res = append(res, left...)
res = append(res, right...)
return res
}
```
This function takes a root node of the binary tree and returns the pre-order traversal of that tree. It first checks if the root is nil or not, and if it is nil, it returns an empty slice. If the root is not nil, it adds the value of the root to the result slice. Then it recursively calls the function on the left subtree and right subtree, and appends the results to the result slice. Finally, it returns the result slice containing the pre-order traversal of the binary tree.