如何在Swift中打印二叉树,使得输入的
79561
打印出以下输出: 7
/ \
5 9
/ \
1 6
我尝试使用For循环
和If语句
编写代码进行排列,但是它没有成功。
我的代码如下:
import UIKit
//Variable "node" used only to arrange it in output.
var node = "0"
var space = " "
var linkLeft = "/"
var linkRight = "\\"
var str = "Hello, playground"
var height = 6
var width = height * 2 + 1
print()
//Height
for h in 1...height {
//Width
for w in 1...width {
switch h {
case 1:
if(w == width/2 + h) {
print(node, terminator: "")
} else {
print(space, terminator: "")
}
if (w == width) {
print()
}
case 2:
//print(linkLeft, terminator: "")
if(w == width/3 + h) {
print(linkLeft, terminator: "")
} else if(w == width/3 + h + 4) {
print(linkRight, terminator: "")
} else {
print(space, terminator: "")
}
if (w == width) {
print()
}
case 3:
if(w == width/5 + h) {
print(node, terminator: "")
} else if(w == width/h + h){
print(node, terminator: "")
} else {
print(space, terminator: "")
}
if (w == width) {
print()
}
break
default:
break
}
}
}
我尝试使用两个For循环
,一个用于高度,另一个用于宽度。但是,如果节点数量发生变化,它将无法正常工作。目前我只尝试调整链接
(/
和\
),节点
和空格的位置,因此它无法正常工作。
有可能有其他方法吗?