golang版本
package main
import (
"fmt"
)
type Node struct {
value int
left *Node
right *Node
}
func newNode(value int) *Node{
return &Node{
value: value,
left: nil,
right: nil,
}
}
type Tree struct {
root *Node
}
func (t *Tree) add (value int) {
node := newNode(value)
if t.root == nil {
t.root = node
return
}
queue := make([]*Node,0)
queue = append(queue, t.root)
for len(queue) > 0 {
subnode := queue[0]
queue = queue[1:]
if subnode.left == nil {
subnode.left = node
return
}
if subnode.right == nil {
subnode.right = node
return
}
queue = append(queue, subnode.left)
queue = append(queue, subnode.right)
}
}
// 广度遍历
func (t *Tree) travel() {
if t.root == nil {
return
}
queue := make([]*Node,0)
queue = append(queue, t.root)
for len(queue) > 0 {
subnode := queue[0]
queue = queue[1:]
fmt.Println(subnode.value)
if subnode.left != nil {
queue = append(queue, subnode.left)
}
if subnode.right != nil {
queue = append(queue, subnode.right)
}
}
}
// 深度优先遍历 先序遍历
func (t *Tree) devTravel(node *Node) {
if node == nil {
return
}
fmt.Println(node.value)
t.devTravel(node.left)
t.devTravel(node.right)
}
func main() {
tree := Tree{}
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.travel()
fmt.Println("*****")
tree.devTravel(tree.root)
}