题目(微软): 输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。 例如输入 8
/ \
6 10
/ \ / \
5 7 9 11 输出8 6 10 5 7 9 11。
二叉树的层序遍历
void BinaryTreeBFS(BinaryTreeNode* proot)
{
if(proot==NULL) return;
deque<BinaryTreeNode*> nodequeue;
BinaryTreeNode* pNode;
nodequeue.push_back(proot);
while (!nodequeue.empty())
{
pNode = nodequeue.front();
cout<<pNode->m_value<<" ";
if(pNode->m_left)
nodequeue.push_back(pNode->m_left);
if(pNode->m_right)
nodequeue.push_back(pNode->m_right);
nodequeue.pop_front();
}
}
顺便付一下二叉树的八种遍历
<span style="font-size:14px;">typedef struct Node {
int data;
struct Node *lchild;
struct Node *rchild;
} *Tree;
1.前序遍历
递归写法:
void PreOrder(Tree root)//递归前序遍历
{
if(root==NULL) return;
cout<<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
非递归写法
void PreOrderNonRecursion(Tree root)//非递归算法
{
stack<Node *> nonstack;
nonstack.push(root);
Node *node;
while(!nonstack.empty())
{
node=nonstack.top();
cout<<node->data;
nonstack.pop();
if(node->rchild)
nonstack.push(node->rchild);
if(node->lchild)
nonstack.push(node->lchild);
}
}
2中序遍历
递归写法:
void InOrder(Tree root)//中序遍历递归
{
if(root!=NULL)
{
InOrder(root->lchild);
cout<<root->data;
InOrder(root->rchild);
}
}
非递归写法
void InOrderNonRecursion(Tree root)//中序非递归算法
{
stack<Node *> nonstack;
Node *node=root;
while(node || !nonstack.empty())
{
if(node)
{
nonstack.push(node);
node=node->lchild;
}
else
{
node=nonstack.top();
cout<<node->data;
nonstack.pop();
node=node.rchild;
}
}
}
3.后序遍历
递归写法:
void PostOrder(Tree root)//后序遍历递归
{
if(root!=NULL)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout<<root->data;
}
}
非递归写法:
void PostOrderNonRecursion(Tree root)
{
stack<Node *> pstack;
Node* node=root;
int flag[20];
while(node)
{
pstack.push(node);
flag[pstack.size()]= 0;
node=node->lchild;
}
while(!pstack.empty())
{
node=pstack.top();
while(node->rchild && flag[pstack.size()]==0)
{
flag[pstack.size()]=1;
node=node->rchild;
while(node)
{
pstack.push(node);
flag[pstack.size()]=0;
node=node->lchild;
}
}
node=pstack.top();
cout<<node->data;
pstack.pop();
}
}
4.深度优先搜索
void DepthFirstTraverse(Tree root)
{
stack<Node*> pstack;
pstack.push(root);
Node *node;
while (!pstack.empty())
{
node=pstack.top();
cout<<node->data;
pstack.pop();
if(node->rchild)
pstack.push(node->rchild);
if(node->lchild)
pstack.push(node->lchild);
}
}
5.广度优先搜索
void BreadFirstTraverse(Tree root)
{
queue<Node *> nodequeue;
nodequeue.push(root);
Node * node;
while(!nodequeue.empty())
{
node=nodequeue.front();
cout<<node->data;
nodequeue.pop();
if(node->lchild)
nodequeue.push(node->lchild);
if(node->rchild)
nodequeue.push(node->rchild);
}
}