編程之美 - 分層遍歷二叉樹

問題描述

一棵二叉樹,按從上到下,從左到右的方式進行遍歷,打印它的所有的節點。

例如二叉樹


pic_01

輸出的結果爲

a

bc

def

 

思路:

二叉樹遍歷的方式爲分層方式


pic_02

每一層都可以看做是一個鏈表,根節點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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章