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

问题描述

一棵二叉树,按从上到下,从左到右的方式进行遍历,打印它的所有的节点。

例如二叉树

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

输出的结果为

a

bc

def

 

思路:

二叉树遍历的方式为分层方式

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

每一层都可以看做是一个链表,根节点level 0可以看做只有一个元素的链表。当遍历level 0时,可以同时将根节点的左右子树放入level 1的链表中。当遍历level1的链表时可以同理生成level2的链表。完成分层遍历。 level 0,level 1,level 2的链表使用同一个链表即可。

代码示例:

#include <iostream>
#include <list>

using namespace std;

typedef struct _node_st
{
    char _data;
    _node_st* _pleft;
    _node_st* _pright;

} node_st;

list<node_st*> node_list;

void print_tree(node_st* proot)
{
    int count = 1;
    int sub_count = 0;
    int i = 0;
    node_st *pnode = NULL;

    node_list.push_back(proot);
    while(count > 0)
    {
        for (i = 0; i < count; i++)
        {
            pnode = node_list.front();
            node_list.pop_front();
            printf("%c ", pnode->_data);
            if (pnode->_pleft)
            {
                node_list.push_back(pnode->_pleft);
                sub_count++;
            }

            if (pnode->_pright)
            {
                node_list.push_back(pnode->_pright);
                sub_count++;
            }
        }
        printf("\n");
        count = sub_count;
        sub_count = 0;
    }
    printf("\n-----------------------------------------\n");
}

node_st* rebuild_pre_in2(char* pre, char* mid, int start, int length)
{
    node_st *node;
    int j = 0;

    if ((length <= 0) || ((pre == NULL) || (mid == NULL)))
       return NULL;

    node = new node_st;
    node->_data = pre[start];
    node->_pleft = node->_pright = NULL;

    if (1 == length)
        return node;

    for (j = 0; j < length; j++)
    {
        if (mid[start+j] == node->_data)
            break;
    }
    node->_pleft  = rebuild_pre_in2(pre, mid, start+1, j);
    node->_pright = rebuild_pre_in2(pre, mid, start+(j+1), length-j-1);

    return node;
}
void main()
{
    char pre[] = {'a','b','d','c','e','f'};
    char mid[] = {'d','b','a','e','c','f'};
    int len = sizeof(pre)/sizeof(pre[0]);

    node_st* proot = NULL;
    proot = rebuild_pre_in2(pre, mid, 0, len);

    print_tree(proot);
    cin>> len;
}

    原文作者:zy__
    原文地址: https://blog.csdn.net/wangzhiyu1980/article/details/52982952
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞