参考:https://blog.csdn.net/qq_33243189/article/details/80222629 package main import "fmt" /** *二叉树 ×××二叉遍历 */ func main() { d := NodeTree{"D", nil, nil} c := NodeTree{"C", &d, nil} b := NodeTree{"B", nil, &c} h := NodeTree{"H", nil, nil} k := NodeTree{"K", nil, nil} g := NodeTree{"G", &h, &k} f := NodeTree{"F", &g, nil} e := NodeTree{"E", nil, &f} a := NodeTree{"A", &b, &e} everyhouxu(&a) } /** 中序遍历:左-根-右 */ func everyzhongxu(node *NodeTree) { if nil == node { return } courrent := node left := courrent.left right := courrent.right if nil == left { fmt.Println(courrent.data) courrent = right everyzhongxu(courrent) return } //输出左孩子 everyzhongxu(left) //输出根节点 fmt.Println(courrent.data) //输出右孩子 everyzhongxu(right) } /** 前序 根左右 */ func everyqianxu(nodetree *NodeTree) { if nil == nodetree { return } courrent := nodetree left := courrent.left right := courrent.right if nil != courrent { fmt.Println(courrent.data) } if nil != left { everyqianxu(left) } if nil != right { everyqianxu(right) } if nil == left && nil == right { return } } /** 后序 左右根 */ func everyhouxu(nodetree *NodeTree) { if nil == nodetree { return } courrent := nodetree left := courrent.left right := courrent.right //左右为页节点时输出 if nil != left { if nil == left.left && nil == left.right { fmt.Print(left.data) } else { everyhouxu(left) } } if nil != right { if nil == right.left && nil == right.right { fmt.Print(right.data) } else { everyhouxu(right) } } if nil != courrent { fmt.Print(courrent.data) } }
/** 层序遍历 */ func cengxu(tree *NodeTree) { if nil == tree { return } var quece [] *NodeTree quece = append(quece, tree) for ; 0 != len(quece); { node := quece[0] fmt.Print(node.Data) quece = quece[1:] //第一个元素出队 if nil != node.Left { //出栈元素的左右元素顺序进队 quece = append(quece, node.Left) } if nil != node.Right { quece = append(quece, node.Right) } } }type NodeTree struct { data string left *NodeTree right *NodeTree }
二叉树的遍历
最新推荐文章于 2024-01-27 15:36:29 发布