具有空值的C ++二进制搜索树级顺序

时间:2018-07-20 18:23:33

标签: c++

我试图按级别顺序打印树,但是如果节点缺少孩子,我想在其位置打印null。我不确定是否需要将语句或将null值推送到队列中。

/* Iterative program to print levels line by line */
#include <iostream>
#include <queue>
using namespace std;

// A Binary Tree Node
struct node
{
    struct node *left;
    int data;
    struct node *right;
};

// Iterative method to do level order traversal line by line
void printLevelOrder(node *root)
{
    // Base Case
    if (root == NULL)  return;

    // Create an empty queue for level order tarversal
    queue<node *> q;

    // Enqueue Root and initialize height
    q.push(root);

    while (1)
    {
        // nodeCount (queue size) indicates number of nodes
        // at current lelvel.
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;

        // Dequeue all nodes of current level and Enqueue all
        // nodes of next level
        while (nodeCount > 0)
        {
            node *node = q.front();
            cout << node->data << " ";
            q.pop();
            if (node->left != NULL)
                q.push(node->left);
            if (node->right != NULL)
                q.push(node->right);
            nodeCount--;
        }
        cout << endl;
    }
}

// Utility function to create a new tree node
node* newNode(int data)
{
    node *temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}

当前输出:

    1 
   / \
  2   3
 /   / \
4   5   6

打印二进制搜索树,不包含任何空值。

预期输出:

                    1 
         /                   \
        2                     3
     /     \               /      \
    4       null         5        6
   / \                 /  \      /  \
null nul             null null null null

使用空值打印二叉树。

对于实现null值的任何指导将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您要打印NULL个子级,只需确保将它们压入队列中,因为您的队列保留了所有将要打印的元素

while (nodeCount > 0)
{
    node *node = q.front();
    q.pop();

    if (!node) {
        cout << "null" << " ";
    } else {
        cout << node->data << " ";
        q.push(node->left);
        q.push(node->right);
    }

    nodeCount--;
}