我想實現一個二叉樹,爲了便於調試,我希望能夠打印樹,使其看起來像一棵樹。例如:在Java中打印二叉樹
50
42 71
31 45 60 98
6 11 43 49 55
或類似的東西。 (樹總是保證完整。)我只需要一個算法或僞代碼來讓我開始。我只是不知道如何實現這樣的東西。感謝您的幫助。
我想實現一個二叉樹,爲了便於調試,我希望能夠打印樹,使其看起來像一棵樹。例如:在Java中打印二叉樹
50
42 71
31 45 60 98
6 11 43 49 55
或類似的東西。 (樹總是保證完整。)我只需要一個算法或僞代碼來讓我開始。我只是不知道如何實現這樣的東西。感謝您的幫助。
哎呀!我知道。我只是爲這個插圖編號。我修好了它。 我不認爲你給我的鏈接中的代碼適用於我的問題。顯然沒有人想用二叉樹來做這些事情。 :/ – thePurpleMonkey
你對將數據存儲爲樹不感興趣,你只是想打印它像一棵樹嗎? – Ric
數據_is_存儲爲樹,我只是不知道如何打印它像一棵樹。 – thePurpleMonkey
我會嘗試着手:(採用使用Python 2.x而不是僞代碼的自由)。
# Doesn't work yet.
# Assumes two characters ('42', '06' etc) per string representation of number.
# If not, alter the formatting %02d as appropriate.
global line_length
line_length=80
def pad(number_of_nodes):
global line_length
return "_"*(line_length/number_of_nodes)
def printlevel(nodes):
global line_length
padstring=pad(len(nodes))
stringnodes=[ "%02d"%(n) for n in nodes ]
leader="_"* abs((line_length/2) - len(padstring))
print leader, padstring.join(stringnodes)
for level in [ [50],
[42,71],
[31,45,60,98],
[6,11,43,49,55]
]:
printlevel(level)
因爲(我相信),問題是超過實際訪問樹節點的格式之一......我剛纔變平樹列表.. 這實際上不起作用的列表,但我認爲它可以重新安排得到它的工作....
這個問題與Python有什麼關係?我認爲這是一個Java問題。 – gparyani
提問者詢問僞代碼以說明需要完成的工作。我使用Python而不是僞代碼。 – monojohnny
其實這已經是一個相當不錯的Java實現在stackoverflow上:http://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram – monojohnny
你正在尋找一個水平順序遍歷。 –