0
我有打印二叉樹的水平的方法:顯示二叉樹的空兒輸出
template<class BTNode>
void breadthfirstByLevel(BTNode* node_ptr) {
if (node_ptr == NULL)
{
return;
}
queue<BTNode *> q1;
queue<BTNode *> q2;
q1.push(node_ptr);
while (!q1.empty() || !q2.empty()) {
while (!q1.empty())
{
node_ptr = q1.front();
q1.pop();
cout << node_ptr->data() << " ";
if (node_ptr->left() != NULL)
{
q2.push(node_ptr->left());
}
if (node_ptr->right() != NULL)
{
q2.push(node_ptr->right());
}
}
cout << endl;
while (!q2.empty())
{
node_ptr = q2.front();
q2.pop();
cout << node_ptr->data() << " ";
if (node_ptr->left() != NULL)
{
q1.push(node_ptr->left());
}
if (node_ptr->right() != NULL)
{
q1.push(node_ptr->right());
}
}
cout << endl;
}
}
我檢查當前節點的孩子爲空,並將其推入隊列。我怎樣才能在電平輸出中顯示「NULL」,而不是隻是跳過它而不打印?