[英]Python Printing Specific Character in Empty Binary Tree Output
I have a binary tree generated as follows我有一个二叉树生成如下
class Node:
def __init__(self,data):
# Left Child
self.left = None
# Right Child
self.right = None
# Node Value
self.data = data
def insert(self, data):
# Compare the new value with the parent node
if self.data:
# Less than or equal goes to the Left
if data <= self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
# Greater than goes to the right
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
Now suppose we populate the binary tree with the following现在假设我们用以下内容填充二叉树
Numbers = [4, 7, 9, 1 , 3]
for index in range(len(Numbers)):
if index == 0:
root = Node(Numbers[index])
else:
root.insert(Numbers[index])
Which generates the following binary tree:生成以下二叉树:
4
/ \
1 7
/ \ / \
. 3 . 9
I have written the following to print the binary tree:我写了以下内容来打印二叉树:
def PrintTree(self, root):
thislevel = [root]
while thislevel:
nextlevel = list()
Curr_Level = ""
for n in thislevel:
Curr_Level += " " + str(n.data)
if n.left:
nextlevel.append(n.left)
if n.right:
nextlevel.append(n.right)
print(Curr_Level)
thislevel = nextlevel
root.PrintTree(root=root)
which generates the following output生成以下 output
4
1 7
3 9
However, I would like the code print the empty entries with an "@", ie I want my code to output the following:但是,我希望代码打印带有“@”的空条目,即我希望我的代码为 output 以下内容:
4
1 7
@ 3 @ 9
How can I go about adjusting my PrintTree
function to achieve this?我 go 如何调整我的
PrintTree
function 来实现这个?
Run a modified version of BFS.运行 BFS 的修改版本。 More specifically, run breadth first search (BFS) starting from the root node.
更具体地说,从根节点开始运行广度优先搜索 (BFS)。 This will assign a level to each node.
这将为每个节点分配一个级别。 During BFS, when a current node has a missing child, add an @ node in its place to the FIFO queue.
在 BFS 期间,当当前节点缺少子节点时,将 @ 节点添加到 FIFO 队列中。 Print a node each time it is removed from the queue.
每次从队列中删除节点时打印一个节点。 Print in a new line each time a node with a new level is removed from the queue.
每次从队列中删除具有新级别的节点时,在新行中打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.