繁体   English   中英

二叉树反向层遍历

[英]Binary Tree reverse level traversal

在此处输入图像描述

我的代码:

void reversrorder(Btree B)
{
    if(!B) return;

    stack s = CreateStack();
    queue q = CreateQueue();
    
    int currentchildcount = 0, nextnumberofchildren = 0, height = 1;
    
    EnQueue(&q, B)
    
    while(Front(q, &B))
    {
        if(currentchildcount >= 0)
        {
            Push(&s, B);
            if(B->left)
            {
                EnQueue(&q, B->left);
                nextnumberofchildren++;
            }
            if(B->right)
            {
                EnQueue(&q, B->right);
                nextnumberofchildren++;
            }
            DeQueue(&q);
            currentchildcount--;
        }
        else
        {
            currentchildcount = nextnumberofchildren;
            nextnumberofchildren = 0;
            height++;
        }
    }
    
    while(Top(s, &B)
    {
        Pop(&s);
        printf("%d ", B->data);
    }
}

我找到了一种方法来检测我何时移动到另一个级别并获得高度,但我无法弄清楚如何在不反转所有元素输出的情况下获得反转级别: 30 15 7 4 20 5 10

我想您将s1定义为堆栈(错字?),但本质上您可以通过首先将孩子排队,然后将孩子排队来解决这个问题。 通过这种方式,您可以生成一个所有级别都反转的级别订单。 最后,当您以相反的顺序对其进行迭代时,已经反转的级别将以“正常”的从左到右的顺序出现。

暂无
暂无

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

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