广告位联系
返回顶部
分享到

Go语言数据结构之二叉树可视化介绍

Golang 来源:互联网 作者:佚名 发布时间:2022-09-18 20:25:37 人浏览
摘要

以图形展示任意二叉树,如下图,一个中缀表达式表示的二叉树:3.14*r*h/3 源代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

以图形展示任意二叉树,如下图,一个中缀表达式表示的二叉树:3.14*r²*h/3

源代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

package main

  

import (

    "fmt"

    "io"

    "os"

    "os/exec"

    "strconv"

    "strings"

)

  

type any = interface{}

  

type btNode struct {

    Data   any

    Lchild *btNode

    Rchild *btNode

}

  

type biTree struct {

    Root *btNode

    Info *biTreeInfo

}

  

type biTreeInfo struct {

    Data                []any

    DataLevel           [][]any

    L, R                []bool

    X, Y, W             []int

    Index, Nodes        int

    Width, Height       int

    MarginX, MarginY    int

    SpaceX, SpaceY      int

    SvgWidth, SvgHeight int

    SvgXml              string

}

  

func Build(Data ...any) *biTree {

    if len(Data) == 0 || Data[0] == nil {

        return &biTree{}

    }

    node := &btNode{Data: Data[0]}

    Queue := []*btNode{node}

    for lst := Data[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 BuildFromList(List []any) *biTree {

    return Build(List...)

}

  

func AinArray(sub int, array []int) int {

    for idx, arr := range array {

        if sub == arr {

            return idx

        }

    }

    return -1

}

  

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) []any {

    var res []any

    if bt != nil {

        L, R := bt.Lchild != nil, bt.Rchild != nil

        res = append(res, []any{bt.Data, L, R, x, y, w})

        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 *biTree) NodeInfo() []any {

    return bt.Root.Coordinate(0, 0, Pow2(bt.Root.MaxDepth()-2))

}

  

func (bt *biTree) TreeInfo() {

    height := bt.Root.MaxDepth()

    width := Pow2(height - 1)

    lsInfo := bt.NodeInfo()

    btInfo := &biTreeInfo{

        Height: height,

        Width:  width,

        Nodes:  len(lsInfo),

    }

    for _, data := range lsInfo {

        for i, info := range data.([]any) {

            switch i {

            case 0:

                btInfo.Data = append(btInfo.Data, info.(any))

            case 1:

                btInfo.L = append(btInfo.L, info.(bool))

            case 2:

                btInfo.R = append(btInfo.R, info.(bool))

            case 3:

                btInfo.X = append(btInfo.X, info.(int))

            case 4:

                btInfo.Y = append(btInfo.Y, info.(int))

            case 5:

                btInfo.W = append(btInfo.W, info.(int))

            }

        }

    }

    for j, k := 0, width*2; j < height; j++ {

        DLevel := []any{}

        for i := k / 2; i < width*2; i += k {

            index := AinArray(i-width, btInfo.X)

            if index > -1 {

                DLevel = append(DLevel, btInfo.Data[index])

            } else {

                DLevel = append(DLevel, nil)

            }

            DLevel = append(DLevel, []int{i, j})

            if k/4 == 0 {

                DLevel = append(DLevel, []int{0, 0})

                DLevel = append(DLevel, []int{0, 0})

            } else {

                DLevel = append(DLevel, []int{i - k/4, j + 1})

                DLevel = append(DLevel, []int{i + k/4, j + 1})

            }

        }

        k /= 2

        btInfo.DataLevel = append(btInfo.DataLevel, DLevel)

    }

    bt.Info = btInfo

}

  

func (bt *biTree) Info2SVG(Margin ...int) string {

    var res, Line, Color string

    info := bt.Info

    MarginX, MarginY := 0, 10

    SpaceX, SpaceY := 40, 100

    switch len(Margin) {

    case 0:

        break

    case 1:

        MarginX = Margin[0]

    case 2:

        MarginX, MarginY = Margin[0], Margin[1]

    case 3:

        MarginX, MarginY, SpaceX = Margin[0], Margin[1], Margin[2]

    default:

        MarginX, MarginY = Margin[0], Margin[1]

        SpaceX, SpaceY = Margin[2], Margin[3]

    }

    info.MarginX, info.MarginY = MarginX, MarginY

    info.SpaceX, info.SpaceY = SpaceX, SpaceY

    info.SvgWidth = Pow2(info.Height)*info.SpaceX + info.SpaceX

    info.SvgHeight = info.Height * info.SpaceY

    for i, Data := range info.Data {

        Node := "\n\t<g id=\"INDEX,M,N\">\n\t<CIRCLE/>\n\t<TEXT/>\n\t<LEAF/>\n\t</g>"

        DataStr := ""

        switch Data.(type) {

        case int:

            DataStr = strconv.Itoa(Data.(int))

        case float64:

            DataStr = strconv.FormatFloat(Data.(float64), 'g', -1, 64)

        case string:

            DataStr = Data.(string)

        default:

            DataStr = "Error Type"

        }

        Node = strings.Replace(Node, "INDEX", strconv.Itoa(info.Index), 1)

        Node = strings.Replace(Node, "M", strconv.Itoa(info.X[i]), 1)

        Node = strings.Replace(Node, "N", strconv.Itoa(info.Y[i]), 1)

        x0, y0 := (info.X[i]+info.Width)*SpaceX+MarginX, 50+info.Y[i]*SpaceY+MarginY

        x1, y1 := x0-info.W[i]*SpaceX, y0+SpaceY-30

        x2, y2 := x0+info.W[i]*SpaceX, y0+SpaceY-30

        Color = "orange"

        if info.L[i] && info.R[i] {

            Line = XmlLine(x0-21, y0+21, x1, y1) + "\n\t" + XmlLine(x0+21, y0+21, x2, y2)

        } else if info.L[i] && !info.R[i] {

            Line = XmlLine(x0-21, y0+21, x1, y1)

        } else if !info.L[i] && info.R[i] {

            Line = XmlLine(x0+21, y0+21, x2, y2)

        } else {

            Color = "lightgreen"

        }

        Node = strings.Replace(Node, "<CIRCLE/>", XmlCircle(x0, y0, Color), 1)

        Node = strings.Replace(Node, "<TEXT/>", XmlText(x0, y0, DataStr), 1)

        if info.L[i] || info.R[i] {

            Node = strings.Replace(Node, "<LEAF/>", Line, 1)

        }

        res += Node

    }

    info.SvgXml = res

    return res

}

  

func XmlCircle(X, Y int, Color string) string {

    Radius := 30

    Circle := "<circle cx=\"" + strconv.Itoa(X) + "\" cy=\"" + strconv.Itoa(Y) +

        "\" r=\"" + strconv.Itoa(Radius) + "\" stroke=\"black\" stroke-width=" +

        "\"2\" fill=\"" + Color + "\" />"

    return Circle

}

  

func XmlText(X, Y int, DATA string) string {

    iFontSize, tColor := 20, "red"

    Text := "<text x=\"" + strconv.Itoa(X) + "\" y=\"" + strconv.Itoa(Y) +

        "\" fill=\"" + tColor + "\" font-size=\"" + strconv.Itoa(iFontSize) +

        "\" text-anchor=\"middle\" dominant-baseline=\"middle\">" + DATA + "</text>"

    return Text

}

  

func XmlLine(X1, Y1, X2, Y2 int) string {

    Line := "<line x1=\"" + strconv.Itoa(X1) + "\" y1=\"" + strconv.Itoa(Y1) +

        "\" x2=\"" + strconv.Itoa(X2) + "\" y2=\"" + strconv.Itoa(Y2) +

        "\" style=\"stroke:black;stroke-width:2\" />"

    return Line

}

  

func (bt *biTree) ShowSVG(FileName ...string) {

    var file *os.File

    var err1 error

    Head := "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink" +

        "=\"http://www.w3.org/1999/xlink\" version=\"1.1\" width=" +

        "\"Width\" height=\"Height\">\nLINKCONTENT\n</svg>"

    Link := `<a xlink:href="https://blog.csdn.net/boysoft2002" target="_blank">

    <text x="5" y="20" fill="blue">Hann's CSDN Homepage</text></a>`

    Xml := strings.Replace(Head, "LINK", Link, 1)

    Xml = strings.Replace(Xml, "Width", strconv.Itoa(bt.Info.SvgWidth), 1)

    Xml = strings.Replace(Xml, "Height", strconv.Itoa(bt.Info.SvgHeight), 1)

    Xml = strings.Replace(Xml, "CONTENT", bt.Info.SvgXml, 1)

    svgFile := "biTree.svg"

    if len(FileName) > 0 {

        svgFile = FileName[0] + ".svg"

    }

    file, err1 = os.Create(svgFile)

    if err1 != nil {

        panic(err1)

    }

    _, err1 = io.WriteString(file, Xml)

    if err1 != nil {

        panic(err1)

    }

    file.Close()

    exec.Command("cmd", "/c", "start", svgFile).Start()

    //Linux 代码:

    //exec.Command("xdg-open", svgFile).Start()

    //Mac 代码:

    //exec.Command("open", svgFile).Start()

}

  

func main() {

  

    list := []any{"*", "*", "*", "/", 5, "*", 3.14, 1, 3, nil, nil, 6, 6}

    tree := Build(list...)

    tree.TreeInfo()

    tree.Info2SVG()

    tree.ShowSVG()

  

    fmt.Println(tree.Info.Data)

    fmt.Println(tree.Info.DataLevel)

  

}

做题思路

增加一个结构biTreeInfo,在遍历二叉树时把作图要用的信息存入此结构中,方便读取信息。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

type any = interface{}

 

type btNode struct {

    Data   any

    Lchild *btNode

    Rchild *btNode

}

 

type biTree struct {

    Root *btNode

    Info *biTreeInfo

}

 

type biTreeInfo struct {

    Data                []any

    DataLevel           [][]any

    L, R                []bool

    X, Y, W             []int

    Index, Nodes        int

    Width, Height       int

    MarginX, MarginY    int

    SpaceX, SpaceY      int

    SvgWidth, SvgHeight int

    SvgXml              string

}

//数据域类型用 type any = interface{} 自定义类型,模拟成any数据类型。

遍历二叉树获取每个结点在svg图形中的坐标,使用先序递归遍历:

1

2

3

4

5

6

7

8

9

10

func (bt *btNode) Coordinate(x, y, w int) []any {

    var res []any

    if bt != nil {

        L, R := bt.Lchild != nil, bt.Rchild != nil

        res = append(res, []any{bt.Data, L, R, x, y, w})

        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

}

二叉树的每个结点,转svg时有圆、文字、左或右直线(叶结点没有真线)。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

func XmlCircle(X, Y int, Color string) string {

    Radius := 30

    Circle := "<circle cx=\"" + strconv.Itoa(X) + "\" cy=\"" + strconv.Itoa(Y) +

        "\" r=\"" + strconv.Itoa(Radius) + "\" stroke=\"black\" stroke-width=" +

        "\"2\" fill=\"" + Color + "\" />"

    return Circle

}

 

func XmlText(X, Y int, DATA string) string {

    iFontSize, tColor := 20, "red"

    Text := "<text x=\"" + strconv.Itoa(X) + "\" y=\"" + strconv.Itoa(Y) +

        "\" fill=\"" + tColor + "\" font-size=\"" + strconv.Itoa(iFontSize) +

        "\" text-anchor=\"middle\" dominant-baseline=\"middle\">" + DATA + "</text>"

    return Text

}

 

func XmlLine(X1, Y1, X2, Y2 int) string {

    Line := "<line x1=\"" + strconv.Itoa(X1) + "\" y1=\"" + strconv.Itoa(Y1) +

        "\" x2=\"" + strconv.Itoa(X2) + "\" y2=\"" + strconv.Itoa(Y2) +

        "\" style=\"stroke:black;stroke-width:2\" />"

    return Line

}

TreeInfo()写入二叉树结点信息,其中DataLevel是层序遍历的结果,也可以用它来作图。

Info2XML()就是把上述方法所得信息,转化成SVG的xml代码;

ShowSVG()生成并显示图形,svg的xml如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="680" height="400">

<a xlink:href="https://blog.csdn.net/boysoft2002" target="_blank">

    <text x="5" y="20" fill="blue">Hann's CSDN Homepage</text></a>

    <g id="0,0,0">

    <circle cx="320" cy="60" r="30" stroke="black" stroke-width="2" fill="orange" />

    <text x="320" y="60" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">*</text>

    <line x1="299" y1="81" x2="160" y2="130" style="stroke:black;stroke-width:2" />

    <line x1="341" y1="81" x2="480" y2="130" style="stroke:black;stroke-width:2" />

    </g>

    <g id="0,-4,1">

    <circle cx="160" cy="160" r="30" stroke="black" stroke-width="2" fill="orange" />

    <text x="160" y="160" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">*</text>

    <line x1="139" y1="181" x2="80" y2="230" style="stroke:black;stroke-width:2" />

    <line x1="181" y1="181" x2="240" y2="230" style="stroke:black;stroke-width:2" />

    </g>

    <g id="0,-6,2">

    <circle cx="80" cy="260" r="30" stroke="black" stroke-width="2" fill="orange" />

    <text x="80" y="260" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">/</text>

    <line x1="59" y1="281" x2="40" y2="330" style="stroke:black;stroke-width:2" />

    <line x1="101" y1="281" x2="120" y2="330" style="stroke:black;stroke-width:2" />

    </g>

    <g id="0,-7,3">

    <circle cx="40" cy="360" r="30" stroke="black" stroke-width="2" fill="lightgreen" />

    <text x="40" y="360" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">1</text>

    <LEAF/>

    </g>

    <g id="0,-5,3">

    <circle cx="120" cy="360" r="30" stroke="black" stroke-width="2" fill="lightgreen" />

    <text x="120" y="360" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">3</text>

    <LEAF/>

    </g>

    <g id="0,-2,2">

    <circle cx="240" cy="260" r="30" stroke="black" stroke-width="2" fill="lightgreen" />

    <text x="240" y="260" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">5</text>

    <LEAF/>

    </g>

    <g id="0,4,1">

    <circle cx="480" cy="160" r="30" stroke="black" stroke-width="2" fill="orange" />

    <text x="480" y="160" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">*</text>

    <line x1="459" y1="181" x2="400" y2="230" style="stroke:black;stroke-width:2" />

    <line x1="501" y1="181" x2="560" y2="230" style="stroke:black;stroke-width:2" />

    </g>

    <g id="0,2,2">

    <circle cx="400" cy="260" r="30" stroke="black" stroke-width="2" fill="orange" />

    <text x="400" y="260" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">*</text>

    <line x1="379" y1="281" x2="360" y2="330" style="stroke:black;stroke-width:2" />

    <line x1="421" y1="281" x2="440" y2="330" style="stroke:black;stroke-width:2" />

    </g>

    <g id="0,1,3">

    <circle cx="360" cy="360" r="30" stroke="black" stroke-width="2" fill="lightgreen" />

    <text x="360" y="360" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">6</text>

    <LEAF/>

    </g>

    <g id="0,3,3">

    <circle cx="440" cy="360" r="30" stroke="black" stroke-width="2" fill="lightgreen" />

    <text x="440" y="360" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">6</text>

    <LEAF/>

    </g>

    <g id="0,6,2">

    <circle cx="560" cy="260" r="30" stroke="black" stroke-width="2" fill="lightgreen" />

    <text x="560" y="260" fill="red" font-size="20" text-anchor="middle" dominant-baseline="middle">3.14</text>

    <LEAF/>

    </g>

</svg>

扩展

多棵二叉树同时展示,Info2SVG()可以设置起始位置

左右并列展示

1

2

3

4

5

6

7

8

9

10

11

tree2 := Build("*", "*", 3.14, 6, 6)

tree2.TreeInfo()

tree2.Info2SVG()

tree2.ShowSVG("tree2")

 

//左右并列展示

tree2.Info2SVG(tree.Info.SvgWidth, tree.Info.SpaceY)

tree.Info.SvgXml += tree2.Info.SvgXml

tree.Info.SvgWidth += tree2.Info.SvgWidth

tree.ShowSVG("tree12")

tree.Info2SVG() //恢复tree原状

上下并列展示

1

2

3

4

5

6

//上下并列展示

tree2.Info2SVG(tree.Info.SvgWidth-tree2.Info.SvgWidth, tree.Info.SvgHeight)

tree.Info.SvgXml += tree2.Info.SvgXml

tree.Info.SvgHeight += tree2.Info.SvgHeight

tree.ShowSVG("tree123")

tree.Info2SVG() //恢复tree原状

以上2段代码放在前文源代码的main()函数中测试。

总结回顾

结点显示的代码固定了文字和圆形的大小颜色,如果读者愿意自己动手的话,可以尝试把这些要素设成参数或者增加biTreeInfo结构的属性。


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 : https://blog.csdn.net/boysoft2002/article/details/126908846
相关文章
  • 基于GORM实现CreateOrUpdate的方法
    CreateOrUpdate 是业务开发中很常见的场景,我们支持用户对某个业务实体进行创建/配置。希望实现的 repository 接口要达到以下两个要求: 如果
  • Golang中的内存逃逸的介绍
    什么是内存逃逸分析 内存逃逸分析是go的编译器在编译期间,根据变量的类型和作用域,确定变量是堆上还是栈上 简单说就是编译器在编译
  • Golang自旋锁的介绍
    自旋锁 获取锁的线程一直处于活跃状态,但是并没有执行任何有效的任务,使用这种锁会造成busy-waiting。 它是为实现保护共享资源而提出的
  • Go语言读写锁RWMutex的源码

    Go语言读写锁RWMutex的源码
    在前面两篇文章中初见 Go Mutex、Go Mutex 源码详解,我们学习了Go语言中的Mutex,它是一把互斥锁,每次只允许一个goroutine进入临界区,可以保
  • Go项目实现优雅关机与平滑重启功能
    什么是优雅关机? 优雅关机就是服务端关机命令发出后不是立即关机,而是等待当前还在处理的请求全部处理完毕后再退出程序,是一种对
  • Go语言操作Excel利器之excelize类库的介绍
    在开发中一些需求需要通过程序操作excel文档,例如导出excel、导入excel、向excel文档中插入图片、表格和图表等信息,使用Excelize就可以方便
  • 利用Go语言快速实现一个极简任务调度系统

    利用Go语言快速实现一个极简任务调度系统
    任务调度(Task Scheduling)是很多软件系统中的重要组成部分,字面上的意思是按照一定要求分配运行一些通常时间较长的脚本或程序。在爬
  • GoLang中的iface 和 eface 的区别介绍

    GoLang中的iface 和 eface 的区别介绍
    GoLang之iface 和 eface 的区别是什么? iface和eface都是 Go 中描述接口的底层结构体,区别在于iface描述的接口包含方法,而eface则是不包含任何方
  • Golang接口使用的教程
    go语言并没有面向对象的相关概念,go语言提到的接口和java、c++等语言提到的接口不同,它不会显示的说明实现了接口,没有继承、子类、
  • go colly 爬虫实现示例介绍
    贡献某CC,go源码爬虫一个,基于colly,效果是根据输入的浏览器cookie及excel必要行列号,从excel中读取公司名称,查询公司法人及电话号码。
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计