GO语言-按树形结构打印二叉树 2024-03-08 默认分类 暂无评论 298 次阅读 ```Go type TreeNode struct { Val int Left, Right *TreeNode } func getTreeDepth(root *TreeNode) int { if root == nil { return 0 } return 1 + int(math.Max(float64(getTreeDepth(root.Left)), float64(getTreeDepth(root.Right)))) } func writeArray(currNode *TreeNode, rowIndex, columnIndex int, res [][]string, treeDepth int) { if currNode == nil { return } res[rowIndex][columnIndex] = fmt.Sprintf("%d", currNode.Val) currLevel := (rowIndex + 1) / 2 if currLevel == treeDepth { return } gap := treeDepth - currLevel - 1 if currNode.Left != nil { res[rowIndex+1][columnIndex-gap] = "/" writeArray(currNode.Left, rowIndex+2, columnIndex-gap*2, res, treeDepth) } if currNode.Right != nil { res[rowIndex+1][columnIndex+gap] = "\\" writeArray(currNode.Right, rowIndex+2, columnIndex+gap*2, res, treeDepth) } } func Show(root *TreeNode) { if root == nil { fmt.Println("EMPTY!") return } treeDepth := getTreeDepth(root) arrayHeight := treeDepth*2 - 1 arrayWidth := (int(math.Pow(2, float64(treeDepth-1))))*3 + 1 res := make([][]string, arrayHeight) for i := 0; i < arrayHeight; i++ { res[i] = make([]string, arrayWidth) for j := 0; j < arrayWidth; j++ { res[i][j] = " " } } writeArray(root, 0, arrayWidth/2, res, treeDepth) for _, line := range res { var sb strings.Builder for i := 0; i < len(line); i++ { sb.WriteString(line[i]) if len(line[i]) > 1 && i <= len(line)-1 { if len(line[i]) > 4 { i += 2 } else { i += len(line[i]) - 1 } } } fmt.Println(sb.String()) } } ``` 测试代码 ```Go func main() { // 创建一个二叉树 root := &TreeNode{Val: 1} root.Left = &TreeNode{Val: 2} root.Right = &TreeNode{Val: 3} root.Left.Left = &TreeNode{Val: 4} root.Left.Right = &TreeNode{Val: 5} root.Right.Left = &TreeNode{Val: 6} root.Right.Right = &TreeNode{Val: 7} // 显示二叉树 Show(root) } ``` ``` 输出内容 1 / \ 2 3 / \ / \ 4 5 6 7 ``` 标签: golang 转载请注明文章来源 本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭