用golang实现二叉树中序遍历,写一下代码。
时间: 2023-03-10 12:21:40 浏览: 106
实现前、中、后序遍历二叉树
package mainimport "fmt"type Node struct {
Val int
Left *Node
Right *Node
}// 中序遍历
func InOrderTraversal(root *Node) {
if root == nil {
return
}
InOrderTraversal(root.Left)
fmt.Println(root.Val)
InOrderTraversal(root.Right)
}func main() {
root := &Node{Val: 1}
root.Left = &Node{Val: 2}
root.Right = &Node{Val: 3}
root.Left.Left = &Node{Val: 4}
root.Left.Right = &Node{Val: 5}
InOrderTraversal(root)
}答:package mainimport "fmt"type Node struct {
Val int
Left *Node
Right *Node
}// 中序遍历
func InOrderTraversal(root *Node) {
if root == nil {
return
}
InOrderTraversal(root.Left)
fmt.Println(root.Val)
InOrderTraversal(root.Right)
}func main() {
root := &Node{Val: 1}
root.Left = &Node{Val: 2}
root.Right = &Node{Val: 3}
root.Left.Left = &Node{Val: 4}
root.Left.Right = &Node{Val: 5}
InOrderTraversal(root)
}答:我可以为您提供Golang实现的二叉树中序遍历的代码:package mainimport "fmt"type Node struct {
Val int
Left *Node
Right *Node
}// 中序遍历
func InOrderTraversal(root *Node) {
if root == nil {
return
}
InOrderTraversal(root.Left)
fmt.Println(root.Val)
InOrderTraversal(root.Right)
}func main() {
root := &Node{Val: 1}
root.Left = &Node{Val: 2}
root.Right = &Node{Val: 3}
root.Left.Left = &Node{Val: 4}
root.Left.Right = &Node{Val: 5}
InOrderTraversal(root)
}
阅读全文