簡體   English   中英

在輸出中顯示二叉樹的空子級

[英]Displaying null children of binary tree in output

我有一種打印二叉樹級別的方法:

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”,而不是僅跳過它而不打印任何內容?

您從隊列中獲取下一個節點的指針以打印數據。 如果此節點有子節點(即,指向子節點的指針不為null),則將其放入隊列中。 這意味着在隊列中永遠不會有nullptr

您可以使用算法的變體來解決此問題:可以在沒有子級的情況下將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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM