题目:输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。

例如输入

8
/ \
6 10
  /\ /\
5 7 9 11

输出8 6 10 5 7 9 11。

 

分析:这曾是微软的一道面试题。这道题实质上是要求遍历一棵二元树,只不过不是我们熟悉的前序、中序或者后序遍历。

我们从树的根结点开始分析。自然先应该打印根结点8,同时为了下次能够打印8的两个子结点,我们应该在遍历到8时把子结点6和10保存到一个数据容器中。现在数据容器中就有两个元素6 和10了。按照从左往右的要求,我们先取出6访问。打印6的同时要把6的两个子结点5和7放入数据容器中,此时数据容器中有三个元素10、5和7。接下来我们应该从数据容器中取出结点10访问了。注意10比5和7先放入容器,此时又比5和7先取出,就是我们通常说的先入先出。因此不难看出这个数据容器的类型应该是个队列。

 

既然已经确定数据容器是一个队列,现在的问题变成怎么实现队列了。实际上我们无需自己动手实现一个,因为STL已经为我们实现了一个很好的deque(两端都可以进出的队列),我们只需要拿过来用就可以了。

我们知道树是图的一种特殊退化形式。同时如果对图的深度优先遍历和广度优先遍历有比较深刻的理解,将不难看出这种遍历方式实际上是一种广度优先遍历。因此这道题的本质是在二元树上实现广度优先遍历。

参考代码:

#include <deque>
#include <iostream>
namespace std;
   4:  
// a node in the binary tree
   6: {
// value of node
// left child of node
// right child of node
  10: };
  11:  
///////////////////////////////////////////////////////////////////////
// Print a binary tree from top level to bottom level
// Input: pTreeRoot - the root of binary tree
///////////////////////////////////////////////////////////////////////
void PrintFromTopToBottom(BTreeNode *pTreeRoot)
  17: {
if(!pTreeRoot)
return;
  20:  
// get a empty queue
  22:       deque<BTreeNode *> dequeTreeNode;
  23:  
// insert the root at the tail of queue
  25:       dequeTreeNode.push_back(pTreeRoot);
  26:  
while(dequeTreeNode.size())
  28:       {
// get a node from the head of queue
  30:             BTreeNode *pNode = dequeTreeNode.front();
  31:             dequeTreeNode.pop_front();
  32:  
// print the node
' ';
  35:  
// print its left child sub-tree if it has
if(pNode->m_pLeft)
  38:                   dequeTreeNode.push_back(pNode->m_pLeft);
// print its right child sub-tree if it has
if(pNode->m_pRight)
  41:                   dequeTreeNode.push_back(pNode->m_pRight);
  42:       }
  43: }

相关文章:

猜你喜欢
  • 2021-12-06
  • 2021-06-26
  • 2022-12-23
  • 2021-12-15
  • 2021-08-20
相关资源
相似解决方案