2024年最全go语言|数据结构:二叉树可视化(svg树形图改进版)_csg树形图,2024年最新瞬间高大上了

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

	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 \n\t \n\t\n\t”
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, “ ”, XmlCircle(x0, y0, Color), 1)
Node = strings.Replace(Node, “ ”, XmlText(x0, y0, DataStr), 1)
if info.L[i] || info.R[i] {
Node = strings.Replace(Node, “”, 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 + “”
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”
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,在遍历二叉树时把作图要用的信息存入此结构中,方便读取信息。



> 
> 
> ```
> 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图形中的坐标,使用先序递归遍历:



> 
> 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时有圆、文字、左或右直线(叶结点没有真线)。



> 
> 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  
>  }
> 
> 
> 




![img](https://img-blog.csdnimg.cn/img_convert/04222dc8ccfa563abc8dceea7cc0b405.png)
![img](https://img-blog.csdnimg.cn/img_convert/984d9437bb2c0bfe889670b0092a96bb.png)

**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**


**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

>  }
> 
> 
> 




[外链图片转存中...(img-IuP5gQ2M-1715630631675)]
[外链图片转存中...(img-yFm2kMBZ-1715630631675)]

**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**


**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

  • 24
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过递归地遍历二叉树,同时记录每个节点的深度和位置信息,然后根据深度和位置信息在输出时进行对齐,就可以实现将二叉树以横向树形结构输出显示的效果。 以下是一个C语言的实现示例,假设二叉树的节点结构如下: ``` typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; ``` 代码如下: ``` void printTree(TreeNode* root) { int depth = getDepth(root); // 获取二叉树的深度 int width = (1 << depth) - 1; // 计算二叉树的宽度 char** arr = (char**)malloc(sizeof(char*) * depth); // 创建一个二维字符数组,用于存储每个节点的值 for (int i = 0; i < depth; i++) { arr[i] = (char*)malloc(sizeof(char) * (width + 1)); memset(arr[i], ' ', width); // 初始空格 arr[i][width] = '\0'; // 结尾加上'\0' } printNode(root, arr, 0, 0, width - 1); // 递归遍历二叉树,记录每个节点的位置信息 for (int i = 0; i < depth; i++) { printf("%s\n", arr[i]); // 输出每一行 free(arr[i]); } free(arr); } int getDepth(TreeNode* root) { if (root == NULL) { return 0; } int leftDepth = getDepth(root->left); int rightDepth = getDepth(root->right); return 1 + (leftDepth > rightDepth ? leftDepth : rightDepth); } void printNode(TreeNode* root, char** arr, int depth, int left, int right) { if (root == NULL) { return; } int mid = (left + right) / 2; arr[depth][mid] = root->val + '0'; // 将节点的值存储在二维字符数组中 printNode(root->left, arr, depth + 1, left, mid - 1); // 递归遍历左子树 printNode(root->right, arr, depth + 1, mid + 1, right); // 递归遍历右子树 } ``` 使用示例: ``` TreeNode* root = createTree(); // 创建一个二叉树 printTree(root); // 输出二叉树的横向树形结构 ``` 其中 `createTree()` 函数需要根据具体情况实现,用于创建一棵二叉树

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值