MCPcopy Index your code
hub / github.com/TheAlgorithms/Go / PrintPyramid

Method PrintPyramid

project_euler/problem_18/tree.go:160–219  ·  view source on GitHub ↗

PrintPyramid is a method that prints the tree as a pyramid

()

Source from the content-addressed store, hash-verified

158
159// PrintPyramid is a method that prints the tree as a pyramid
160func (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)

Callers

nothing calls this directly

Calls 7

isInQueueMethod · 0.95
ValueMethod · 0.65
LeftIsNilMethod · 0.65
GetIDMethod · 0.65
LeftMethod · 0.65
RightIsNilMethod · 0.65
RightMethod · 0.65

Tested by

no test coverage detected