go语言|二叉树递归遍历,可能有你没见过的花样玩法

简介: go语言|二叉树递归遍历,可能有你没见过的花样玩法

9ddddd890441439cb5ed1a979e45dca6.png在上一篇博客《go语言|数据结构:二叉树可视化(制作svg格式树形图)》中,已实现了用svg图片展示二叉树的树形结构。但对非满二叉树的比较复杂,需要先转成满二叉树,再获取各结点在满二叉树中的对应坐标位置,这种做法明显有个缺点就是遍历的次数比较多。


树形图的关键在于获取结点的坐标。对满二叉树的来说,它的坐标数组可以标记为:[[(0,0)], [(1,0), (1,1)], [(2,0), (2,1), (2,2), (2,3)], [(3,0),(3,1), ...], ...];如能对任意二叉树只做一次遍布,就获得这样的坐标,效率就提高了。首先,从递归遍历说起——




递归遍历


递归遍历时,看数据域和左右子树结点出现的位置顺序看,分先序、中序、后序三种方式。不管哪种方式都可以用2种方法,一种是直接打印遍历结果、一种返回遍历结果(结点的数据域数组)。如下代码,以先序遍历为例:

package main
import "fmt"
type btNode struct {
  Data   interface{}
  Lchild *btNode
  Rchild *btNode
}
type biTree struct {
  Root *btNode
}
func Build(List ...interface{}) *biTree {
  if len(List) == 0 || List[0] == nil {
    return &biTree{}
  }
  node := &btNode{Data: List[0]}
  Queue := []*btNode{node}
  for lst := List[1:]; len(lst) > 0 && len(Queue) > 0; {
    cur, val := Queue[0], lst[0]
    Queue, lst = Queue[1:], lst[1:]
    if val != nil {
      cur.Lchild = &btNode{Data: val}
      Queue = append(Queue, cur.Lchild)
    }
    if len(lst) > 0 {
      val, lst = lst[0], lst[1:]
      if val != nil {
        cur.Rchild = &btNode{Data: val}
        Queue = append(Queue, cur.Rchild)
      }
    }
  }
  return &biTree{Root: node}
}
func (bt *btNode) PreorderPrint() {
  if bt != nil {
    fmt.Print(bt.Data, " ")
    bt.Lchild.PreorderPrint()
    bt.Rchild.PreorderPrint()
  }
}
func (bt *btNode) PreorderList() []interface{} {
  var res []interface{}
  if bt != nil {
    res = append(res, bt.Data)
    res = append(res, bt.Lchild.PreorderList()...)
    res = append(res, bt.Rchild.PreorderList()...)
  }
  return res
}
func main() {
  tree := Build(1, 2, 3, 4, 5, 6, 7, 8)
  fmt.Println(tree.Root.PreorderList())
  tree.Root.PreorderPrint()
}


创建函数Build()也作了改进,直接用变长参数,而非之前用数组作参数。另外,参数中如有不能连接的结点,直接放弃而非抛出错误panic()。如参数 1,nil,nil,2,3 就只返回一个结点。



深度的遍历


递归遍历核心就以下三行代码,先读出数据域,后左右递归的即先序遍历;读出放中间或最后一行就变成中序和后序遍历了。


 

fmt.Print(bt.Data, " ")                //读出数据域
    bt.Lchild.PreorderPrint()          //左子树递归
    bt.Rchild.PreorderPrint()          //右子树递归

如果把bt.Data换成其它呢,结点结构就定义了三个值,换成bt.Lchild,bt.Rchild就能遍历出左右子树结点。这样用处不大, 如果写成 bt.Lchild!=nil 或者 bt.Rchild!=nil,遍历结果就是该结点是否有左子树或右子树;写成 bt.Lchild==nil && bt.Rchild==nil 就能判断是否为叶结点。如果换作一个自定义函数呢,那就能得到自己想要的结果。也可以玩其它花样,比如累加所有结点的和,为了方便默认它们的数据域都是整数:


//相同代码部分略,见上面的代码
func (bt *btNode) SumTree() int {
  var res int
  if bt != nil {
    res += bt.Data.(int)
    res += bt.Lchild.SumTree()
    res += bt.Rchild.SumTree()
  }
  return res
}
func main() {
  tree := Build(1, 5, 26, 9, 8, 51)
  fmt.Println(tree.Root.SumTree())
}
// 输出结果 100



深度和高度的概念


深度是从根节点数到它的叶节点,高度是从叶节点数到它的根节点。即深度是从上到下计数的,而高度是从下往上计数。


二叉树的深度是指所有结点中最深的结点所在的层数。对于整棵树来说,最深的叶结点的深度就是树的深度,即树的高度和深度是相等的。但同一层的节点的深度是相同,它们的高度不一定相同。如下图,节点2和3的深度相等,但高度不相等;节点4、5、6深度也相等,但高度不全相等。

baf17268732246b89af38e904dd07fa0.png



深度的遍历

从二叉树深度的定义可知,二叉树的深度应为其左、右子树深度的最大值加1。由此,需先分别求得左、右子树的深度,算法中“访问结点”的操作为:求得左、右子树深度的最大值,然后加 1 。递归代码如下:

func (bt *btNode) MaxDepth() int {
  if bt == nil {
    return 0
  }
  Lmax := bt.Lchild.MaxDepth()
  Rmax := bt.Rchild.MaxDepth()
  if Lmax > Rmax {
    return 1 + Lmax
  } else {
    return 1 + Rmax
  }
}



遍历时用上这个函数就可得到所有结点的深度了,完整测试代码以8个结点的完全二叉树为例,返回结果是:“4 3 2 1 1 2 1 1”。最大值4为根结点的尝试,也就是整个二叉树的深度或高度;四个最小值1,表示有四个叶结点。

package main
import "fmt"
type btNode struct {
  Data   interface{}
  Lchild *btNode
  Rchild *btNode
}
type biTree struct {
  Root *btNode
}
func Build(List ...interface{}) *biTree {
  if len(List) == 0 || List[0] == nil {
    return &biTree{}
  }
  node := &btNode{Data: List[0]}
  Queue := []*btNode{node}
  for lst := List[1:]; len(lst) > 0 && len(Queue) > 0; {
    cur, val := Queue[0], lst[0]
    Queue, lst = Queue[1:], lst[1:]
    if val != nil {
      cur.Lchild = &btNode{Data: val}
      Queue = append(Queue, cur.Lchild)
    }
    if len(lst) > 0 {
      val, lst = lst[0], lst[1:]
      if val != nil {
        cur.Rchild = &btNode{Data: val}
        Queue = append(Queue, cur.Rchild)
      }
    }
  }
  return &biTree{Root: node}
}
func (bt *btNode) PreorderDepth() {
  if bt != nil {
    fmt.Print(bt.MaxDepth(), " ")
    bt.Lchild.PreorderDepth()
    bt.Rchild.PreorderDepth()
  }
}
func (bt *btNode) MaxDepth() int {
  if bt == nil {
    return 0
  }
  Lmax := bt.Lchild.MaxDepth()
  Rmax := bt.Rchild.MaxDepth()
  if Lmax > Rmax {
    return 1 + Lmax
  } else {
    return 1 + Rmax
  }
}
func main() {
  tree := Build(1, 2, 3, 4, 5, 6, 7, 8)
  tree.Root.PreorderDepth()
}



叶结点的遍历

func (bt *btNode) LeafPrint() {
  if bt != nil {
    if bt.Lchild == nil && bt.Rchild == nil {
      fmt.Print(bt.Data, " ")
    }
    bt.Lchild.LeafPrint()
    bt.Rchild.LeafPrint()
  }
}
func (bt *btNode) LeafList() []interface{} {
  var res []interface{}
  if bt != nil {
    if bt.Lchild == nil && bt.Rchild == nil {
      res = append(res, bt.Data)
    }
    res = append(res, bt.Lchild.LeafList()...)
    res = append(res, bt.Rchild.LeafList()...)
  }
  return res
}

结点结构的三变量都用过了,对得到结点的坐标帮助不大,坐标需要的是结点在树中的层数和所在层数的索引号。于是尝试引入其它变量——



坐标的遍历


纵坐标遍历

//相同代码部分略,见上面的代码
func (bt *btNode) LevelPrint(y int) {
  if bt != nil {
    fmt.Print(bt.Data, ":", y, " ")
        y++
    bt.Lchild.LevelPrint(y)
    bt.Rchild.LevelPrint(y)
        y--
  }
}
func main() {
  tree := Build(1, 2, 3, 4, 5, 6, 7, 8)
  tree.Root.LevelPrint(0)
}
//输出结果 1:0 2:1 4:2 8:3 5:2 3:1 6:2 7:2

a6cd915bda0c441cbe72086eef1b4c04.png

改成返回数组形式如下: 另外也可以把y++,y--改成参数y+1,输出[0 1 2 3 2 1 2 2],结果相同。

//相同代码部分略,见上面的代码
func (bt *btNode) LevelList(y int) []int {
  var res []int
  if bt != nil {
    res = append(res, y)
    res = append(res, bt.Lchild.LevelList(y+1)...)
    res = append(res, bt.Rchild.LevelList(y+1)...)
  }
  return res
}
func main() {
  tree := Build(1, 2, 3, 4, 5, 6, 7, 8)
  fmt.Print(tree.Root.LevelList(0))
}



横坐标遍历

依葫芦画瓢,照纵坐标的方式遍历:

func (bt *btNode) IndexPrint(x int) {
  if bt != nil {
    fmt.Print(bt.Data, ":", x, " ")
    bt.Lchild.IndexPrint(x - 1)
    bt.Rchild.IndexPrint(x + 1)
  }
}

但结果不符合要求:1:0 2:-1 4:-2 8:-3 5:0 3:1 6:0 7:2

a6e76e2bd002444bbe1165c6658c3cd1.png



最底下一层最靠近中间的左右两结点横坐标是-1,1就OK了,以满二叉树为例来说比较好理解:

15a36b1a61ca4df68eddfbbafade78bd.png



从上图的规律看,每层平移的距离不一样的,不能平移正负1,移动距离应该是2的高度减一次方才对,调用时参数为(0,2的高度-2次方),完整的测试代码如下:

package main
import "fmt"
type btNode struct {
  Data   interface{}
  Lchild *btNode
  Rchild *btNode
}
type biTree struct {
  Root *btNode
}
func Build(List ...interface{}) *biTree {
  if len(List) == 0 || List[0] == nil {
    return &biTree{}
  }
  node := &btNode{Data: List[0]}
  Queue := []*btNode{node}
  for lst := List[1:]; len(lst) > 0 && len(Queue) > 0; {
    cur, val := Queue[0], lst[0]
    Queue, lst = Queue[1:], lst[1:]
    if val != nil {
      cur.Lchild = &btNode{Data: val}
      Queue = append(Queue, cur.Lchild)
    }
    if len(lst) > 0 {
      val, lst = lst[0], lst[1:]
      if val != nil {
        cur.Rchild = &btNode{Data: val}
        Queue = append(Queue, cur.Rchild)
      }
    }
  }
  return &biTree{Root: node}
}
func Pow2(x int) int { //x>=0
  res := 1
  for i := 0; i < x; i++ {
    res *= 2
  }
  return res
}
func Max(L, R int) int {
  if L > R {
    return L
  } else {
    return R
  }
}
func (bt *btNode) MaxDepth() int {
  if bt == nil {
    return 0
  }
  Lmax := bt.Lchild.MaxDepth()
  Rmax := bt.Rchild.MaxDepth()
  return 1 + Max(Lmax, Rmax)
}
func (bt *btNode) IndexPrint(x, w int) {
  if bt != nil {
    fmt.Print(bt.Data, ":", x, " ")
    bt.Lchild.IndexPrint(x-w, w/2)
    bt.Rchild.IndexPrint(x+w, w/2)
  }
}
func main() {
  tree := Build(1, 2, 3)
  tree.Root.IndexPrint(0, Pow2(tree.Root.MaxDepth()-2))
  fmt.Println()
  tree = Build(1, 2, 3, 4, 5, 6, 7)
  tree.Root.IndexPrint(0, Pow2(tree.Root.MaxDepth()-2))
  fmt.Println()
  tree = Build(1, 2, 3, 4, 5, 6, 7, 8)
  tree.Root.IndexPrint(0, Pow2(tree.Root.MaxDepth()-2))
  fmt.Println()
  tree = Build(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
  tree.Root.IndexPrint(0, Pow2(tree.Root.MaxDepth()-2))
  fmt.Println()
}
/*输出结果
1:0 2:-1 3:1 
1:0 2:-2 4:-3 5:-1 3:2 6:1 7:3 
1:0 2:-4 4:-6 8:-7 5:-2 3:4 6:2 7:6 
1:0 2:-4 4:-6 8:-7 9:-5 5:-2 10:-3 11:-1 3:4 6:2 12:1 13:3 7:6 14:5 15:7 
*/


横纵坐标联合输出

综上,把横纵坐标放一起以数组形式输出,参数多一个是变动的平移距离:

//相同代码部分略,见上面的代码
func (bt *btNode) Coordinate(x, y, w int) []interface{} {
  var res []interface{}
  if bt != nil {
    res = append(res, []interface{}{bt.Data, x, y})
    res = append(res, bt.Lchild.Coordinate(x-w, y+1, w/2)...)
    res = append(res, bt.Rchild.Coordinate(x+w, y+1, w/2)...)
  }
  return res
}
func main() {
  tree := Build(1, 2, 3)
  fmt.Println(tree.Root.Coordinate(0, 0, Pow2(tree.Root.MaxDepth()-2)))
  tree = Build(1, 2, 3, 4, 5, 6, 7)
  fmt.Println(tree.Root.Coordinate(0, 0, Pow2(tree.Root.MaxDepth()-2)))
  tree = Build(1, 2, 3, nil, nil, 5, 6, 7, 8)
  fmt.Println(tree.Root.Coordinate(0, 0, Pow2(tree.Root.MaxDepth()-2)))
  tree = Build(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
  fmt.Println(tree.Root.Coordinate(0, 0, Pow2(tree.Root.MaxDepth()-2)))
  tree = Build(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
  fmt.Println(tree.Root.Coordinate(0, 0, Pow2(tree.Root.MaxDepth()-2)))
}
/*输出结果
[[1 0 0] [2 -1 1] [3 1 1]]
[[1 0 0] [2 -2 1] [4 -3 2] [5 -1 2] [3 2 1] [6 1 2] [7 3 2]]
[[1 0 0] [2 -4 1] [3 4 1] [5 2 2] [7 1 3] [8 3 3] [6 6 2]]
[[1 0 0] [2 -4 1] [4 -6 2] [8 -7 3] [9 -5 3] [5 -2 2] [10 -3 3] [11 -1 3] [3 4 1] [6 2 2] [12 1 3] [13 3 3] [7 6 2] [14 5 3] [15 7 3]]
[[1 0 0] [2 -8 1] [4 -12 2] [8 -14 3] [16 -15 4] [9 -10 3] [5 -4 2] [10 -6 3] [11 -2 3] [3 8 1] [6 4 2] [12 2 3] [13 6 3] [7 12 2] [14 10 3] [15 14 3]]
*/


至此,坐标遍历全部完成,再加上判断有否左右子树结点就能作图了:

package main
import "fmt"
type btNode struct {
  Data   interface{}
  Lchild *btNode
  Rchild *btNode
}
type biTree struct {
  Root *btNode
}
func Build(List ...interface{}) *biTree {
  if len(List) == 0 || List[0] == nil {
    return &biTree{}
  }
  node := &btNode{Data: List[0]}
  Queue := []*btNode{node}
  for lst := List[1:]; len(lst) > 0 && len(Queue) > 0; {
    cur, val := Queue[0], lst[0]
    Queue, lst = Queue[1:], lst[1:]
    if val != nil {
      cur.Lchild = &btNode{Data: val}
      Queue = append(Queue, cur.Lchild)
    }
    if len(lst) > 0 {
      val, lst = lst[0], lst[1:]
      if val != nil {
        cur.Rchild = &btNode{Data: val}
        Queue = append(Queue, cur.Rchild)
      }
    }
  }
  return &biTree{Root: node}
}
func Pow2(x int) int { //x>=0
  res := 1
  for i := 0; i < x; i++ {
    res *= 2
  }
  return res
}
func Max(L, R int) int {
  if L > R {
    return L
  } else {
    return R
  }
}
func (bt *btNode) MaxDepth() int {
  if bt == nil {
    return 0
  }
  Lmax := bt.Lchild.MaxDepth()
  Rmax := bt.Rchild.MaxDepth()
  return 1 + Max(Lmax, Rmax)
}
func (bt *btNode) Coordinate(x, y, w int) []interface{} {
  var res []interface{}
  if bt != nil {
    res = append(res, []interface{}{bt.Data, x, y, w, bt.Lchild != nil, bt.Rchild != nil})
    res = append(res, bt.Lchild.Coordinate(x-w, y+1, w/2)...)
    res = append(res, bt.Rchild.Coordinate(x+w, y+1, w/2)...)
  }
  return res
}
func main() {
  tree := Build(1, 2, 3, 4, 5, 6, 7, 8)
  list := tree.Root.Coordinate(0, 0, Pow2(tree.Root.MaxDepth()-2))
  fmt.Println(list)
  //数组的遍历
  for _, data := range list {
    for _, d := range data.([]interface{}) {
      fmt.Print(d, " ")
    }
    /*内循环或者用:
    for i, _ := range data.([]interface{}) {
      fmt.Print(data.([]interface{})[i], " ")
    }
    */
    fmt.Println()
  }
}
/*输出结果
[[1 0 0 true true] [2 -4 1 true true] [4 -6 2 true false] [8 -7 3 false false] [5 -2 2 false false] [3 4 1 true true] [6 2 2 false false] [7 6 2 false false]]
1 0 0 true true 
2 -4 1 true true 
4 -6 2 true false 
8 -7 3 false false 
5 -2 2 false false 
3 4 1 true true 
6 2 2 false false 
7 6 2 false false 
*/


作图时的用法,以上面完整代码的输出为例:


遍历到 2 -4 1 2 true true ,表示(-4,1)处是结点2,true true就有2条子树的连线,指向坐标 (-4-2, 1+1) (-4+2, 1+1),即 (-6, 2) 和 (-2, 2),即结点4和结点;

遍历到 4 -6 2 1 true false,表示(-6,2)处是结点4,true false说明它只有左子树,指向坐标 (-7,3),即结点8;

遍历到 8 -7 3 0 false false,表示(-7,3)处是结点8,false,false说明它是叶结点。


具体如何把结点和坐标转换到二叉树svg图形格式,请参见上篇文章:


《go语言|数据结构:二叉树可视化(制作svg格式树形图)》。

BTW,以上所有代码不论是哪一个递归遍历都可以有三种顺序,比如坐标遍历的代码:

//先序
func (bt *btNode) Coordinate(x, y, w int) []interface{} {
  var res []interface{}
  if bt != nil {
    res = append(res, []interface{}{bt.Data, x, y})
    res = append(res, bt.Lchild.Coordinate(x-w, y+1, w/2)...)
    res = append(res, bt.Rchild.Coordinate(x+w, y+1, w/2)...)
  }
  return res
}


换个顺序就成为中序和后序遍历:

//中序
func (bt *btNode) Coordinate(x, y, w int) []interface{} {
  var res []interface{}
  if bt != nil {
    res = append(res, bt.Lchild.Coordinate(x-w, y+1, w/2)...)
    res = append(res, []interface{}{bt.Data, x, y})
    res = append(res, bt.Rchild.Coordinate(x+w, y+1, w/2)...)
  }
  return res
}
//后序
func (bt *btNode) Coordinate(x, y, w int) []interface{} {
  var res []interface{}
  if bt != nil {
    res = append(res, bt.Lchild.Coordinate(x-w, y+1, w/2)...)
    res = append(res, bt.Rchild.Coordinate(x+w, y+1, w/2)...)
    res = append(res, []interface{}{bt.Data, x, y})
  }
  return res
}

(本文完)

目录
相关文章
|
10天前
|
程序员 Go PHP
为什么大部分的 PHP 程序员转不了 Go 语言?
【9月更文挑战第8天】大部分 PHP 程序员难以转向 Go 语言,主要因为:一、编程习惯与思维方式差异,如语法风格和编程范式;二、学习成本高,需掌握新知识体系且面临项目压力;三、职业发展考量,现有技能价值及市场需求不确定性。学习新语言虽有挑战,但对拓宽职业道路至关重要。
40 10
|
8天前
|
Go API 开发者
深入探讨:使用Go语言构建高性能RESTful API服务
在本文中,我们将探索Go语言在构建高效、可靠的RESTful API服务中的独特优势。通过实际案例分析,我们将展示Go如何通过其并发模型、简洁的语法和内置的http包,成为现代后端服务开发的有力工具。
|
10天前
|
算法 程序员 Go
PHP 程序员学会了 Go 语言就能唬住面试官吗?
【9月更文挑战第8天】学会Go语言可提升PHP程序员的面试印象,但不足以 solely “唬住” 面试官。学习新语言能展现学习能力、拓宽技术视野,并增加就业机会。然而,实际项目经验、深入理解语言特性和综合能力更为关键。全面展示这些方面才能真正提升面试成功率。
34 10
|
10天前
|
编译器 Go
go语言学习记录(关于一些奇怪的疑问)有别于其他编程语言
本文探讨了Go语言中的常量概念,特别是特殊常量iota的使用方法及其自动递增特性。同时,文中还提到了在声明常量时,后续常量可沿用前一个值的特点,以及在遍历map时可能遇到的非顺序打印问题。
|
8天前
|
存储 监控 数据可视化
Go 语言打造公司监控电脑的思路
在现代企业管理中,监控公司电脑系统对保障信息安全和提升工作效率至关重要。Go 语言凭借其高效性和简洁性,成为构建监控系统的理想选择。本文介绍了使用 Go 语言监控系统资源(如 CPU、内存)和网络活动的方法,并探讨了整合监控数据、设置告警机制及构建可视化界面的策略,以满足企业需求。
25 1
|
15天前
|
安全 大数据 Go
深入探索Go语言并发编程:Goroutines与Channels的实战应用
在当今高性能、高并发的应用需求下,Go语言以其独特的并发模型——Goroutines和Channels,成为了众多开发者眼中的璀璨明星。本文不仅阐述了Goroutines作为轻量级线程的优势,还深入剖析了Channels作为Goroutines间通信的桥梁,如何优雅地解决并发编程中的复杂问题。通过实战案例,我们将展示如何利用这些特性构建高效、可扩展的并发系统,同时探讨并发编程中常见的陷阱与最佳实践,为读者打开Go语言并发编程的广阔视野。
|
12天前
|
存储 Shell Go
Go语言结构体和元组全面解析
Go语言结构体和元组全面解析
|
17天前
|
Go
golang语言之go常用命令
这篇文章列出了常用的Go语言命令,如`go run`、`go install`、`go build`、`go help`、`go get`、`go mod`、`go test`、`go tool`、`go vet`、`go fmt`、`go doc`、`go version`和`go env`,以及它们的基本用法和功能。
25 6
|
17天前
|
存储 Go
Golang语言基于go module方式管理包(package)
这篇文章详细介绍了Golang语言中基于go module方式管理包(package)的方法,包括Go Modules的发展历史、go module的介绍、常用命令和操作步骤,并通过代码示例展示了如何初始化项目、引入第三方包、组织代码结构以及运行测试。
19 3
|
1天前
|
Shell Go API
Go语言grequests库并发请求的实战案例
Go语言grequests库并发请求的实战案例