开发者

Need help with tree-printing code

I am trying to print this tree:

    1 
   / \
  2   3
 /   / \
4   5   6

In this way:

1
2 3
4 5 6

I wrote this code:

void print_g(Tree t)
{
    Queue q=initQueue();
    Tree tmp=initTree();
    if(!isTreeEmpty(t))
        enqueue(q,t);
    while(!isQueueEmpty(q))
    {
        tmp=dequeue(q);
        printf("%d ",*((int *)Root(tmp)));
        if(!isTreeEmpty(subLeft(tmp)))
            enqueue(q,subLeft(tmp));
        if(!isTreeEmpty(subRight(tmp)))
            enqueue(q,subRight(tmp));

    }
}

But this code is printed like this:

123456

I can't think o开发者_JAVA百科f an idea how to solve the print issue. Can someone write the Pseudo Code??

Thanks.


After you add the children to the queue, create a fake tree node with the value being a newline character and add it to the queue.


You don't have any code to print a newline ('\n') after each generation of the tree.

You need to find some way to tell your program when a tree generation passes and then stick the '\n' in there.

Perhaps:

void print_g(Tree t)
{
    Queue q=initQueue();
    Tree tmp=initTree();
    if(!isTreeEmpty(t))
        enqueue(q,t);

    int dist = distanceFromTop(t); // new function to tell us which generation we are in

    while(!isQueueEmpty(q))
    {
        tmp=dequeue(q);

        if (distanceFromTop(tmp) != dist) // have we changed generation from previous iteration?
            printf("\n"); // if so, newline
        dist = distanceFromTop(tmp);

        printf("%d ",*((int *)Root(tmp)));
        if(!isTreeEmpty(subLeft(tmp)))
            enqueue(q,subLeft(tmp));
        if(!isTreeEmpty(subRight(tmp)))
            enqueue(q,subRight(tmp));

    }
}

Just be sure that your Tree definition has a member to hold its own distanceFromTop and fill this value in during initTree() to keep the algorithm from getting too slow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜