PrintPyramid is a method that prints the tree as a pyramid
()
| 158 | |
| 159 | // PrintPyramid is a method that prints the tree as a pyramid |
| 160 | func (t *Tree) PrintPyramid() { |
| 161 | t.Nodes = make(map[int]struct{}) |
| 162 | if t.Root == nil { |
| 163 | return |
| 164 | } |
| 165 | |
| 166 | queue := []Node{t.Root} |
| 167 | levels := []int{0} |
| 168 | outputByLevel := []string{} |
| 169 | |
| 170 | head := 0 |
| 171 | currentLevel := 0 |
| 172 | |
| 173 | output := "" |
| 174 | |
| 175 | for head < len(queue) { |
| 176 | current := queue[head] |
| 177 | level := levels[head] |
| 178 | head++ |
| 179 | |
| 180 | // Level change |
| 181 | if level > currentLevel { |
| 182 | currentLevel = level |
| 183 | outputByLevel = append(outputByLevel, output+"\n") |
| 184 | output = "" |
| 185 | } |
| 186 | |
| 187 | // Add current node to the output |
| 188 | if current.Value() < 10 { |
| 189 | output += fmt.Sprintf("0%d ", current.Value()) |
| 190 | } else { |
| 191 | output += fmt.Sprintf("%d ", current.Value()) |
| 192 | } |
| 193 | |
| 194 | // Add children to the queue |
| 195 | if !current.LeftIsNil() { |
| 196 | if !t.isInQueue(current.Left().GetID()) { |
| 197 | queue = append(queue, current.Left()) |
| 198 | levels = append(levels, level+1) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | if !current.RightIsNil() { |
| 203 | if !t.isInQueue(current.Right().GetID()) { |
| 204 | queue = append(queue, current.Right()) |
| 205 | levels = append(levels, level+1) |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | // Add the last level |
| 210 | outputByLevel = append(outputByLevel, output+"\n") |
| 211 | |
| 212 | totalLevels := len(outputByLevel) |
| 213 | |
| 214 | // Print the pyramid |
| 215 | for i, level := range outputByLevel { |
| 216 | str := strings.Repeat(" ", 2*(totalLevels-i)) + level |
| 217 | print(str) |