17-- 从上到下打印二叉树,按层打印。

//
//  main.cpp
//  subStructureInTree
//
//  Created by Hugo Cao  on 15/7/10.
//  Copyright (c) 2015年 Hugo Cao . All rights reserved.
//

/*
 问题描述:
    从上到下打印二叉树,按层打印。
    思路:这里用队列实现了转化。很有意思的想法。
 
 */

#include <iostream>
#include <deque>
using namespace std;
#define Data int

typedef struct binaaryTreeNode
{
    Data m_value;
    binaaryTreeNode *m_pleft;
    binaaryTreeNode *m_pright;
}btNode, *binTree;

binTree addNode(Data value)
{
    binTree bt = NULL;
    bt = new btNode;
    if (bt == NULL)
    {
        cout << "申请地址错误" << endl;
        return NULL;
    }
    
    bt->m_value = value;
    bt->m_pleft = NULL;
    bt->m_pright = NULL;
    
    return bt;
}

bool connectTreeNode(binTree parrentNode, binTree leftSonNode = NULL, binTree rightSonNode = NULL)
{
    if (parrentNode == NULL || (leftSonNode == NULL && rightSonNode == NULL))
    {
        cout << "结点输入问题" << endl;
        return false;
    }
    parrentNode->m_pleft  = leftSonNode;
    parrentNode->m_pright = rightSonNode;
    return true;
}

binTree createBinaryATree(binTree Ahead)
{
    binTree p1 = addNode(8);
    binTree p2 = addNode(8);
    binTree p3 = addNode(7);
    binTree p4 = addNode(9);
    binTree p5 = addNode(2);
    binTree p6 = addNode(4);
    binTree p7 = addNode(7);
    
    connectTreeNode(p1, p2, p3);
    connectTreeNode(p2, p4, p5);
    connectTreeNode(p5, p6, p7);
    
    return (Ahead = p1);
}


//按层打印
void PrintFromTopToButtom(binTree bt)
{
    //如果是空结点就退出
    if (!bt)
    {
        return ;
    }
    //使用队列作为模型
    deque<binTree> dequeTreeNode;
    dequeTreeNode.push_back(bt);    //将根结点压入队列
    
    //栈为空的时候退出循环
    while (dequeTreeNode.size()) 
    {
        //返回队列头指针
        binTree pNode = dequeTreeNode.front();
        printf("%d\n", pNode->m_value);     //打印向量信息
        dequeTreeNode.pop_front();          //弹出
        
        //层遍历,其实也是先左后右,向队列压入元素。
        if (pNode->m_pleft)
        {
            dequeTreeNode.push_back(pNode->m_pleft);
        }
        if (pNode->m_pright)
        {
            dequeTreeNode.push_back(pNode->m_pright);
        }
    }

}

//打印二叉树
void BLR_print_BinaryTree(binTree bt)
{
    if (bt == NULL)
        return ;
    
    cout << bt->m_value << "  " << endl;
    BLR_print_BinaryTree(bt->m_pleft);
    BLR_print_BinaryTree(bt->m_pright);
}


int main()
{
    binTree bt_A = NULL;
    bt_A = createBinaryATree(bt_A);
    PrintFromTopToButtom(bt_A);
    cout << endl;
    
   
    return 0;
}

 

posted on 2015-09-27 19:06  HGonlyWJ  阅读(226)  评论(0编辑  收藏  举报

W3C中国
阮老师的网络日志
canvas
runoob
迷渡
并发编程网
原生JS例子
前端外刊评论