我正在尝试使用stdout而不是print来获取BST的输出。问题是当标准输出显示值似乎混乱时。
我尝试过像sys.stdout.write(' '.join(str(x) for x in str(node.data)))
这样的事情。和sys.stdout.write(str(node.data))
。代码如下。
import sys
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# function to convert sorted array to a
# balanced BST
# input : sorted array of integers
# output: root node of balanced BST
def sort_array_to_bst(arr):
if not arr:
return None
# find middle
mid = (len(arr)) / 2
mid = int(mid)
# make the middle element the root
root = Node(arr[mid])
# left subtree of root has all
# values <arr[mid]
root.left = sort_array_to_bst(arr[:mid])
# right subtree of root has all
# values >arr[mid]
root.right = sort_array_to_bst(arr[mid + 1:])
return root
# A utility function to print the preorder
# traversal of the BST
def pre_order(node):
if not node:
return
#sys.stdout.write(' '.join(str(x) for x in str(node.data)))
# Output : 5 71 5 78 9 83 9 72 61 7 86 7 9
#sys.stdout.write(str(node.data))
# Output: 5715789839726178679
#print(node.data, end=" ")
pre_order(node.left)
pre_order(node.right)
arr = [7, 898, 157, 397, 57, 178, 26, 679]
root = sort_array_to_bst(arr[1:])
pre_order(root)
预计产量为57 157 898 397 26 178 679
。
但正如在sys.stdout.write(' '.join(str(x) for x in str(node.data)))
的代码中所评论的那样,我得到了输出5 71 5 78 9 83 9 72 61 7 86 7 9
而对于sys.stdout.write(str(node.data))
,我得到输出5715789839726178679
。
反正有没有实现这个目标?
你在' '.join()
上调用str(node.data)
,这意味着它将需要57
并加入57
的每个字符之间的空格。试着在sys.stdout.write(str(node.data) + ' ')
函数中用pre_order()
替换stdout。
在迭代之前,不应将node.data
转换为字符串;否则你将迭代字符串的各个字符。
更改:
sys.stdout.write(' '.join(str(x) for x in str(node.data)))
至:
sys.stdout.write(' '.join(str(x) for x in node.data))