|
| 1 | +package print_binary_tree |
| 2 | + |
| 3 | +import ( |
| 4 | + "math" |
| 5 | + "strconv" |
| 6 | + |
| 7 | + serialize_and_deserialize_binary_tree "github.com/masx200/leetcode-test/serialize-and-deserialize-binary-tree" |
| 8 | + |
| 9 | + maximum_depth_of_binary_tree "github.com/masx200/leetcode-test/maximum-depth-of-binary-tree" |
| 10 | +) |
| 11 | + |
| 12 | +var maxDepth = maximum_depth_of_binary_tree.MaxDepth |
| 13 | + |
| 14 | +type TreeNode = serialize_and_deserialize_binary_tree.TreeNode |
| 15 | +type BinaryTreePosition struct { |
| 16 | + node *TreeNode |
| 17 | + row int |
| 18 | + col int |
| 19 | +} |
| 20 | + |
| 21 | +func Pow(a, b int) int { |
| 22 | + return int(math.Pow(float64(a), float64(b))) |
| 23 | +} |
| 24 | + |
| 25 | +func printTree(root *TreeNode) [][]string { |
| 26 | + if root == nil { |
| 27 | + return [][]string{} |
| 28 | + } |
| 29 | + var depth = maxDepth(root) |
| 30 | + var height = depth - 1 |
| 31 | + var m = depth |
| 32 | + var n = (Pow(2, (m)) - 1) |
| 33 | + var result [][]string = make([][]string, m) |
| 34 | + for i := 0; i < m; i++ { |
| 35 | + result[i] = make([]string, n) |
| 36 | + } |
| 37 | + var cur []BinaryTreePosition = []BinaryTreePosition{{node: root, row: 0, col: ((n - 1) / 2)}} |
| 38 | + |
| 39 | + for len(cur) > 0 { |
| 40 | + var next []BinaryTreePosition = make([]BinaryTreePosition, 0) |
| 41 | + |
| 42 | + for _, entry := range cur { |
| 43 | + var node = entry.node |
| 44 | + var row = entry.row |
| 45 | + var col = entry.col |
| 46 | + if node != nil { |
| 47 | + result[row][col] = strconv.Itoa(node.Val) |
| 48 | + if node.Left != nil { |
| 49 | + next = append(next, BinaryTreePosition{ |
| 50 | + node: node.Left, |
| 51 | + row: row + 1, |
| 52 | + col: col - Pow(2, height-1-row), |
| 53 | + }) |
| 54 | + } |
| 55 | + if node.Right != nil { |
| 56 | + next = append(next, BinaryTreePosition{node: node.Right, |
| 57 | + row: row + 1, |
| 58 | + col: col + Pow(2, (height-1-row)), |
| 59 | + }) |
| 60 | + |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + cur = next |
| 65 | + } |
| 66 | + return result |
| 67 | +} |
0 commit comments