您的位置:首页 > 职场人生

面试题23:从上往下打印二叉树

2016-12-21 14:52 246 查看


#include <deque>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

struct BinaryTreeNode
{
int  m_value;
BinaryTreeNode*  m_pLeft;
BinaryTreeNode*  m_pRight;
}*TPP,TPPP;

void PrintFromToptoBottom(BinaryTreeNode* pTreeRoot)
{
if(pTreeRoot == NULL)
return;

BinaryTreeNode *pCurrent;// = pTreeRoot;
deque<BinaryTreeNode*> p;
p.push_back(pTreeRoot);
while(p.size())
{
pCurrent = p.front();
p.pop_front();

cout<<pCurrent->m_value<<"  ";

if(pCurrent->m_pLeft)
{
p.push_back(pCurrent->m_pLeft);
}
if(pCurrent->m_pRight)
{
p.push_back(pCurrent->m_pRight);

}

}

}

void CreateBinaryTree(BinaryTreeNode* &T)
{
int value;
cin>>value;
if(value == -1)
return;
else
{

BinaryTreeNode *t;
t=(BinaryTreeNode*)malloc(sizeof(BinaryTreeNode));
t->m_value=value;
t->m_pLeft=NULL;
t->m_pRight=NULL;
T=t;
CreateBinaryTree(T->m_pLeft);
CreateBinaryTree(T->m_pRight);
}

}

void inorder(BinaryTreeNode * &pTree)
{
if(pTree)
{
cout<<pTree->m_value<<"   ";
inorder(pTree->m_pLeft);
inorder(pTree->m_pRight);
}
}

int main()
{
BinaryTreeNode *pTree = NULL;

CreateBinaryTree(pTree);
inorder(pTree);
PrintFromToptoBottom(pTree);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试题