题目(微软):
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
例如输入
输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
例如输入
8
/ /
6 10
/ / / /
5 7 9 11
输出8 6 10 5 7 9 11。
这里要建一个队列,把左右孩子入队列,然后打印对头节点的值!
#include <iostream>
#include <queue>
using namespace std;
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
BSTreeNode();
BSTreeNode(int value);
};
void insert(BSTreeNode** root,int n); //树的插入操作
void inversive(BSTreeNode* root); //树的反转
int main()
{
BSTreeNode* root = NULL;
insert(&root,8);
insert(&root,6);
insert(&root,10);
insert(&root,5);
insert(&root,7);
insert(&root,9);
insert(&root,11);
inversive(root);
return 0;
}
void insert(BSTreeNode** root,int n)
{
BSTreeNode* temp = new BSTreeNode;
BSTreeNode* current ;
temp->m_nValue = n ;
temp->m_pLeft = NULL ;
temp->m_pRight = NULL ;
if (*root == NULL)
{
*root = new BSTreeNode(n);
}
else
{
current = *root ;
while(current != NULL)
{
if (current->m_nValue>n&¤t->m_pLeft==NULL)
{
current->m_pLeft = temp ;
break;
}
else if (current->m_nValue>n&¤t->m_pLeft!=NULL)
{
current = current->m_pLeft;
continue;
}
else if (current->m_nValue<n&¤t->m_pRight==NULL)
{
current->m_pRight = temp;
break;
}
else if (current->m_nValue<n&¤t->m_pRight!=NULL)
{
current = current->m_pRight;
continue;
}
}
}
}
BSTreeNode::BSTreeNode(int value)
{
m_nValue = value ;
m_pLeft = NULL ;
m_pRight = NULL ;
}
BSTreeNode::BSTreeNode()
{}
void inversive(BSTreeNode* root)
{
queue<BSTreeNode*> q ;
BSTreeNode* temp = root;
BSTreeNode* nowswap = NULL;
q.push(temp);
while (!q.empty())
{
temp = q.front();
q.pop();
if (temp->m_pLeft != NULL)
q.push(temp->m_pLeft);
if (temp->m_pRight != NULL)
q.push(temp->m_pRight);
std::cout<<temp->m_nValue<<" ";
}
}