编程之美--分层遍历二叉树

1.输出二叉树某一层结点(从左到右)

把输出二叉树第K层结点转换成:分别输出"以该二叉树根结点的左右子树为根的两棵子树"中第K-1层结点。

void PrintNodeAtLevel(Node *root , int level)
{
    if(!root || level < 0)
        return ;
    if(level == 0)
    {
        printf("%c", root->chValue);
    }
    PrintNodeAtLevel(root->lChild , level - 1);
    PrintNodeAtLevel(root->rChild , level - 1);
}

2.按层从上到下遍历二叉树,每一层单独一行且从左往右输出。

front为队首指针,指向队首元素,rear为队尾指针,指向队尾元素的下一个位置。

void InitQueue()
{
    front = rear = 0;
}

void EnQueue(Node *p)
{
    Q[rear++] = p;
}

Node *DeQueue()
{
    return Q[front++];
}

void PrintNodeByLevel(Node *root)
{
    int last;
    Node *p;

    if(!root)    return ;

    InitQueue();
    EnQueue(root);
    while(front < rear)
    {
        last = rear;
        while(front < last)
        {
            p = DeQueue();
            printf("%c", p->chValue);
            if(p->lChild)    EnQueue(p->lChild);
            if(p->rChild)    EnQueue(p->rChild);
        }
        printf("\n");
    }
}

3.扩展问题

依然是按层遍历二叉树,只是要求从下往上访问,并且每一层中结点的访问顺序为从右向左。

分析:只要层与层之间加入哑元素(NULL),然后逆序输出队列Q即可.

void PrintNodeByLevel(Node *root)
{
    int last;
    Node *p;

    if(!root)    return ;

    InitQueue();
    EnQueue(root);
    EnQueue(NULL);
    while(front < rear - 1)
    {
        last = rear - 1;
        while(front < last)
        {
            p = DeQueue();
            if(p->lChild)    EnQueue(p->lChild);
            if(p->rChild)    EnQueue(p->rChild);
        }
        EnQueue(NULL);
        front = last + 1;
    }
}

第二步:逆序输出队列Q


for(int i = rear - 2 ; i >= 0 ; i--)
{
    if(Q[i] == NULL)
        printf("\n");
    else
        printf("%c", Q[i]->chValue);
}
4.百度一道面试题

输出二叉树第 m 层的第 k 个节点值(m, k 均从 0 开始计数)
递归方法:

利用||从左往右的计算顺序以及其真值关系。

int Print(Node *root , int m , int *cnt)
{
    if(!root || m < 0)
        return 0;
    if(m == 0)
    {
        if(*cnt == k)
        {
            printf("%c", root->chValue);
            return 1;
        }
        *cnt += 1;
        return 0;
    }
    return Print(root->lChild , m - 1 , cnt) || Print(root->rChild , m - 1 , cnt);
}

非递归方法:

按照先前层次遍历的方法找到第m层,第k个结点,然后输出,代码略



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值