c++ - 在输出中显示二叉树的空子节点

标签 c++ tree breadth-first-search

我有一个打印二叉树层次的方法:

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”而不是跳过它并且不打印任何内容?

最佳答案

你从队列中取出下一个节点的指针来打印数据。如果此节点有子节点(即指向子节点的指针不为空),则将它们放入队列中。这意味着在队列中永远不会有 nullptr

您可以使用该算法的变体来解决这个问题:您可以在没有 child 的情况下将 nullptr 放入队列中。但是你必须确保当你从队列中获取指针时不要取消引用它们。

...
while (!q1.empty() || !q2.empty()) {
    while (!q1.empty())
    {
        node_ptr = q1.front();
        q1.pop();
        if (node_ptr==nullptr) {    // if nullptr was on queue
            cout << "<NULL> ";      // tell it 
        }
        else {                      // otherwise handle data and queue its children  
            cout << node_ptr->data() << " "; 
            q2.push(node_ptr->left());    // push even if it's nullptr
            q2.push(node_ptr->right());   //       "           "   
        }
    }
    ... // then same for q2
}

关于c++ - 在输出中显示二叉树的空子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40227235/

相关文章:

performance - 广度优先搜索分支因子

algorithm - 如何找到所有最短路径

c++ - 我如何在 C++ 中将双(**)指针用于一般树数据结构?

c++ - 打印一般树级别

javascript - Javascript 中的递归树插入

c++ - 用C++在最后插入

java - 查找数字组合以求和为一个数字

C++ 表达式 : vector subscript out of range error Line:1733

c++ - 如果我将一个 POD 结构分配给另一个 POD 结构,是否存在内存泄漏?

c++ - 基于 malloc/free 的 STL 分配器