[算法]剑指offer p23二叉树层级遍历 golang
题目
题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。例如输入图中的二叉树,则依次打印出 8 6 10 5 7 9 11
节点定义
type BTree struct {
value int
left *BTree
right *BTree
}
解法1
思路是: 使用队列维护节点
package main
import (
"fmt"
"testing"
"github.com/dengjiawen8955/gostl/ds/queue"
"github.com/stretchr/testify/assert"
)
func TestP23(t *testing.T) {
a8 := &BTree{value: 8}
a6 := &BTree{value: 6}
a10 := &BTree{value: 10}
a5 := &BTree{value: 5}
a7 := &BTree{value: 7}
a9 := &BTree{value: 9}
a11 := &BTree{value: 11}
a8.left = a6
a8.right = a10
a6.left = a5
a6.right = a7
a10.left = a9
a10.right = a11
except := []int{8, 6, 10, 5, 7, 9, 11}
assert.Equal(t, except, printFromTopToBottom(a8))
}
//层序遍历二叉树
func printFromTopToBottom(root *BTree) (order []int) {
//参数检查
if root == nil {
fmt.Printf("%s\n", "err: root is nil")
}
order = make([]int, 0)
//层顺序遍历
que := queue.NewQueue()
que.Push(root)
for {
//退出条件
if que.IsEmpty() {
break
}
//输出
node := que.Pop().(*BTree)
order = append(order, node.value)
//推入左子树和右子树
if node.left != nil {
que.Push(node.left)
}
if node.right != nil {
que.Push(node.right)
}
}
return order
}