简体   繁体   English

在输出中显示二叉树的空子级

[英]Displaying null children of binary tree in output

I have a method that prints the levels of a binary tree: 我有一种打印二叉树级别的方法:

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;
    }
    }

I check for the children of the current node to be null and push them into the queue. 我检查当前节点的子节点是否为空并将其推入队列。 How can I display "NULL" in the level output instead of just skipping it and printing nothing? 如何在级别输出中显示“ NULL”,而不是仅跳过它而不打印任何内容?

You take the pointer of the next node from the queue to print data. 您从队列中获取下一个节点的指针以打印数据。 If this node has children (ie pointer to child not null), you put them in the queue. 如果此节点有子节点(即,指向子节点的指针不为null),则将其放入队列中。 This means that in the queue you'll never have a nullptr . 这意味着在队列中永远不会有nullptr

You can solve this using a variant of the algorithm: you could put nullptr in the queue in absence of child. 您可以使用算法的变体来解决此问题:可以在没有子级的情况下将nullptr放入队列中。 But you then have to make sure when you get pointers from the queue not to dereference them. 但是,然后必须确保从队列中获取指针时不要取消引用它们。

...
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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM