横向打印树
水平打印树,选择右中左遍历的原因。右树在根节点的上面,左树在根节点的下面,按照从上到下的顺序打印就是右中左的遍历方式。
def printTree(root, depth=0):
s = ''
if not root:
return s
sright = printTree2(root.right, depth+1)
print('\033[5;30m|\033[0m '*depth+"\033[1;31m"+root.val+"\033[0m")
sleft = printTree2(root.left, depth+1)
# s = sright + '| '*depth + root.val + '\n' + sleft
# return s
打印效果
纵向打印树
层序遍历可以满足纵向一行一行打印的需求,按照中序遍历打印顺序,给每个节点添加index属性,控制离最左端的距离。
def printTree(root):
if not root:
return
index = -1
# 中序遍历树,按打印顺序给节点添加index属性
stack = []
head = root
while root or stack:
while root:
stack.append(root)
root = root.left
finish = stack.pop()
index += 1
finish.index = index
root = finish.right
maxindex = index
# 层序遍历
queue = deque()
queue.append(head)
symbol = ' + '
while queue:
n = len(queue)
s = ""
lastindex = -1
for i in range(n):
finish = queue.popleft()
s += symbol * (finish.index-lastindex-1) + " \033[1;31m"+finish.val+"\033[0m "
lastindex = finish.index
if finish.left:
queue.append(finish.left)
if finish.right:
queue.append(finish.right)
s += symbol * (maxindex-lastindex)
print(s)
打印效果