也许是快速/简单的问题。我已经实现了一个二叉树,然后我希望将二叉搜索树转换为数组,或者至少像在数组中一样打印出来。我遇到的问题是如何获取 '\0' 中的 NULL/标志。
例如,假设我有一棵树,如下所示:
10
/ \
6 12
/ \ \
1 8 15
\
4
我希望它按其应有的方式打印。喜欢:
[10,6,12,1,8,\0,15,\0,4,\0,\0,\0,\0,\0,\0]
^Something Like this^ I don't know if I counted the NULL correctly.
或者我想如何以视觉方式显示我的树的另一个选项是如何正确输出间距,就像使用指向父级的键的“/”和“\”一样:
10
/ \
6 12
/ \ \
1 8 15
\
4
这是我尝试在代码方面详细阐述的内容,但我卡住了:
void BreadthFirstTravseral(struct node* root)
{
queue<node*> q;
if (!root) {
return;
}
for (q.push(root); !q.empty(); q.pop()) {
const node * const temp_node = q.front();
cout<<temp_node->data << " ";
if (temp_node->left) {
q.push(temp_node->left);
}
if (temp_node->right) {
q.push(temp_node->right);
}
}
}
任何类型的帮助或链接和/或建议和/或示例代码将非常感激。