如何按级别的顺序打印二进制搜索树,包括零值
因此,现在,当我有一棵看起来像这样的树时:
5
\
6
\
7
\
9
我可以按级别的顺序打印它,以便
5,
6,
7,
9,
打印出来
,我想制作它,以便它打印出类似的东西:
5,
0, 6,
0, 0, 0, 7,
0, 0, 0, 0, 0, 0, 0, 9,
以便所有无效的节点也被打印为0。
void current_height(tree *root, int level){
if(root == NULL){
return;
}
if(level == 1){
printf("%d, ", root->data);
}
else if(level > 1){
current_height(root->left, level - 1);
current_height(root->right, level - 1);
}
}
这是我到目前为止的代码
,我还考虑将索引放入struct树中,以便我可以将树更改为阵列并打印数组。 但是我发现它会使删除功能过于复杂,所以我没有使用这个想法
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,在每个节点上调用
Current_height
(在该节点上遍历整个子树),使该算法效率低下。您可以使用此想法:
创建一个用于存储当前节点级别的数组。确保它的大小可以包含底层。
在索引0存储根参考。
然后迭代级别:
打印当前数组中的节点的数据
用两个孩子替换每个节点 - 或当节点实际上是
null
时,请放两个null
null 数组中的值。为了避免在读取数据之前覆盖该数据,请从最右边的节点向后填充数组到索引0,然后将子节点从右到左列入子节点。这样,父母就不会覆盖他们。
这是一个实现:
请注意,您的
高度
功能返回树中的级别数。 “高度”的标准定义是从根到其最远的叶子的路径的长度,以边缘数表示(请参见 wikipedia )。因此,只有一个节点的树具有高度0,一个空的树(null
)的高度-1。这就是为什么以上代码从height()
调用返回的值中减去1的原因。First of all, calling
current_height
on each node (which traverses the whole subtree on that node), makes this algorithm inefficient.You could use this idea:
Create an array for storing the current level of nodes. Make sure it is has a size that can contain the bottom level.
At index 0 store the root reference.
Then iterate the levels:
Print the data of the nodes that are currently in the array
Replace each node with its two children -- or when the node was actually a
NULL
, put twoNULL
values in the array.To avoid that data is overwritten before it is read, iterate the array from the rightmost filled-in node backwards to index 0, and store the child nodes also from right to left. This way there is no overwriting of parents before they are read.
Here is an implementation:
Note that your
height
function returns the number of levels in the tree. The standard definition of "height" is the length of the path from root to its furthest leaf, expressed in number of edges (see Wikipedia). So a tree with just one node has height 0, and an empty tree (NULL
) has height -1. This is why the above code subtracts 1 from the value that theheight()
call returns.对于清晰的BFS视图,我们通常在DSA问题中看到的视图,
请参阅参考,请参阅附加的图像
我们可以在Python中遵循此功能或方法
For clear BFS view like the view which we generally see in DSA questions
for reference see the image attached
BFS including null values
we can follow this function or approach in python
您必须模拟不存在的树内容。
由于您已经有有关相对目标级别的信息,因为您的附加参数已经到位,这并不难。
只需在目标深度之前发明更多的树节点,始终将无效的指针作为发明的指针。
在这里输出 https://wwwwwwwww.onlinegdb.com/online_c_compiler
You have to simulate tree content which is not there.
Since you have the info on the relative target level as your additional parameter already in place that is not hard.
Just invent more tree nodes in case of NULL pointers before the target depth, always giving NULL as invented pointer.
Output here https://www.onlinegdb.com/online_c_compiler is: