程序員面試題精選100題(12)-從上往下遍歷二元樹[數據結構]

題目:輸入一顆二元樹,從上往下按層打印樹的每個結點,同一層中按照從左往右的順序打印。

例如輸入

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

輸出8   6   10   5   7   9   11。

分析:這曾是微軟的一道面試題。這道題實質上是要求遍歷一棵二元樹,只不過不是我們熟悉的前序、中序或者後序遍歷。

我們從樹的根結點開始分析。自然先應該打印根結點8,同時爲了下次能夠打印8的兩個子結點,我們應該在遍歷到8時把子結點610保存到一個數據容器中。現在數據容器中就有兩個元素10了。按照從左往右的要求,我們先取出6訪問。打印6的同時要把6的兩個子結點57放入數據容器中,此時數據容器中有三個元素1057。接下來我們應該從數據容器中取出結點10訪問了。注意1057先放入容器,此時又比57先取出,就是我們通常說的先入先出。因此不難看出這個數據容器的類型應該是個隊列。

既然已經確定數據容器是一個隊列,現在的問題變成怎麼實現隊列了。實際上我們無需自己動手實現一個,因爲STL已經爲我們實現了一個很好的deque(兩端都可以進出的隊列),我們只需要拿過來用就可以了。

我們知道樹是圖的一種特殊退化形式。同時如果對圖的深度優先遍歷和廣度優先遍歷有比較深刻的理解,將不難看出這種遍歷方式實際上是一種廣度優先遍歷。因此這道題的本質是在二元樹上實現廣度優先遍歷。

參考代碼:

#include <deque>
#include <iostream>
using namespace std;

struct BTreeNode // a node in the binary tree
{
      int         m_nValue; // value of node
      BTreeNode  *m_pLeft;  // left child of node
      BTreeNode  *m_pRight; // right child of node
};

///////////////////////////////////////////////////////////////////////
// Print a binary tree from top level to bottom level
// Input: pTreeRoot - the root of binary tree
///////////////////////////////////////////////////////////////////////
void PrintFromTopToBottom(BTreeNode *pTreeRoot)
{
      if(!pTreeRoot)
            return;

      // get a empty queue
      deque<BTreeNode *> dequeTreeNode;

      // insert the root at the tail of queue
      dequeTreeNode.push_back(pTreeRoot);

      while(dequeTreeNode.size())
      {
            // get a node from the head of queue
            BTreeNode *pNode = dequeTreeNode.front();
            dequeTreeNode.pop_front();

            // print the node
            cout << pNode->m_nValue << ' ';

            // print its left child sub-tree if it has
            if(pNode->m_pLeft)
                  dequeTreeNode.push_back(pNode->m_pLeft);
            // print its right child sub-tree if it has
            if(pNode->m_pRight)
                  dequeTreeNode.push_back(pNode->m_pRight);
      }
}


轉自:http://zhedahht.blog.163.com/blog/static/2541117420072199173643/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章