剑指——从上往下打印二叉树(按层遍历)

从上往下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

思路:每一次打印一个节点的时候,如果该节点有子节点,则把该节点的子节点放到一个队列的末尾,接下来到队列的头部取出最早进入队列的节点,重复前面的打印操作,直至队列中所有节点都被打印出来为止

#include <stdio.h>
#include <iostream>
#include <deque>
using namespace std;

struct BinaryTree
{
  int m_value;
  struct BinaryTree* leftChild;
  struct BinaryTree* rightChild;
};

//index 设置为&类型 则此函数调用后index会发生改变
BinaryTree* createTree(BinaryTree* root,int* s,int& index)
{
    if(s[index]==0)  //如果第一个是0则代表为空
        return NULL;
    root=new BinaryTree;
    root->m_value=s[index];
    root->leftChild=createTree(root->leftChild,s,++index);
    root->rightChild=createTree(root->rightChild,s,++index);
    return root;
}

//前序遍历
void preTraverse(BinaryTree* root)
{
    if(root==NULL)
        return;
    cout<<root->m_value<<endl;
    preTraverse(root->leftChild);
    preTraverse(root->rightChild);
}

//按层遍历
void PrintFromTopToBottom(BinaryTree* root)
{
    if(root==NULL)  //判断节点是否为空
        return ;
    deque<BinaryTree*> dequeTreeNode;
    dequeTreeNode.push_back(root); //将不为空的节点添加到deque中
    while(dequeTreeNode.size()>0)  //循环结束条件是deque中是否有值
    {
        BinaryTree* tmp=dequeTreeNode.front(); //存储将要po的节点
        dequeTreeNode.pop_front();
        cout<<tmp->m_value<<endl;
        if(tmp->leftChild)  //判断pop出的节点是否有左子节点
            dequeTreeNode.push_back(tmp->leftChild);
        if(tmp->rightChild) //判断pop出的节点是否有右子节点
            dequeTreeNode.push_back(tmp->rightChild);
    }
}

int main()
{
    //输入的时候,不能忘记用0来补充NULL值
    int Tree[]={8,6,5,0,0,7,0,0,10,9,0,0,11,0,0};
    int index=0;
    BinaryTree* root=NULL;
    root=createTree(root,Tree,index);

    preTraverse(root);
    cout<<"----"<<endl;

    PrintFromTopToBottom(root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/SwordArcher/article/details/79960288