python输出一棵松树,在python中逐级打印二叉树

下面是我的尝试,使用递归,并跟踪每个节点的大小和子节点的大小。class BstNode:

def __init__(self, key):

self.key = key

self.right = None

self.left = None

def insert(self, key):

if self.key == key:

return

elif self.key < key:

if self.right is None:

self.right = BstNode(key)

else:

self.right.insert(key)

else: # self.key > key

if self.left is None:

self.left = BstNode(key)

else:

self.left.insert(key)

def display(self):

lines, _, _, _ = self._display_aux()

for line in lines:

print(line)

def _display_aux(self):

"""Returns list of strings, width, height, and horizontal coordinate of the root."""

# No child.

if self.right is None and self.left is None:

line = '%s' % self.key

width = len(line)

height = 1

middle = width // 2

return [line], width, height, middle

# Only left child.

if self.right is None:

lines, n, p, x = self.left._display_aux()

s = '%s' % self.key

u = len(s)

first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s

second_line = x * ' ' + '/' + (n - x - 1 + u) * ' '

shifted_lines = [line + u * ' ' for line in lines]

return [first_line, second_line] + shifted_lines, n + u, p + 2, n + u // 2

# Only right child.

if self.left is None:

lines, n, p, x = self.right._display_aux()

s = '%s' % self.key

u = len(s)

first_line = s + x * '_' + (n - x) * ' '

second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' '

shifted_lines = [u * ' ' + line for line in lines]

return [first_line, second_line] + shifted_lines, n + u, p + 2, u // 2

# Two children.

left, n, p, x = self.left._display_aux()

right, m, q, y = self.right._display_aux()

s = '%s' % self.key

u = len(s)

first_line = (x + 1) * ' ' + (n - x - 1) * '_' + s + y * '_' + (m - y) * ' '

second_line = x * ' ' + '/' + (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' '

if p < q:

left += [n * ' '] * (q - p)

elif q < p:

right += [m * ' '] * (p - q)

zipped_lines = zip(left, right)

lines = [first_line, second_line] + [a + u * ' ' + b for a, b in zipped_lines]

return lines, n + m + u, max(p, q) + 2, n + u // 2

import random

b = BstNode(50)

for _ in range(50):

b.insert(random.randint(0, 100))

b.display()

示例输出:__50_________________________________________

/ \

________________________43_ ________________________99

/ \ /

_9_ 48 ____________67_____________________

/ \ / \

3 11_________ 54___ ______96_

/ \ \ \ / \

0 8 ____26___________ 61___ ________88___ 97

/ \ / \ / \

14_ __42 56 64_ 75_____ 92_

/ \ / / \ / \ / \

13 16_ 33_ 63 65_ 72 81_ 90 94

\ / \ \ / \

25 __31 41 66 80 87

/ /

28_ 76

\

29

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值