求二叉樹的深度 (轉載)

題目:輸入一棵二元樹的根結點,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。

例如:輸入二元樹:

                                           10
                                          /    \
                                        6       14
                                      /         /   \
                                    4        12     16

輸出該樹的深度3

二元樹的結點定義如下:

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

分析:這道題本質上還是考查二元樹的遍歷。

題目給出了一種樹的深度的定義。當然,我們可以按照這種定義去得到樹的所有路徑,也就能得到最長路徑以及它的長度。只是這種思路用來寫程序有點麻煩。

我們還可以從另外一個角度來理解樹的深度。如果一棵樹只有一個結點,它的深度爲1。如果根結點只有左子樹而沒有右子樹,那麼樹的深度應該是其左子樹的深度加1;同樣如果根結點只有右子樹而沒有左子樹,那麼樹的深度應該是其右子樹的深度加1。如果既有右子樹又有左子樹呢?那該樹的深度就是其左、右子樹深度的較大值再加1

上面的這個思路用遞歸的方法很容易實現,只需要對遍歷的代碼稍作修改即可。參考代碼如下:

///////////////////////////////////////////////////////////////////////
// Get depth of a binary tree
// Input: pTreeNode - the head of a binary tree
// Output: the depth of a binary tree
///////////////////////////////////////////////////////////////////////
int TreeDepth(SBinaryTreeNode *pTreeNode)
{
     // the depth of a empty tree is 0
     if(!pTreeNode)
           return 0;

     // the depth of left sub-tree
     int nLeft = TreeDepth(pTreeNode->m_pLeft);
     // the depth of right sub-tree
     int nRight = TreeDepth(pTreeNode->m_pRight);

     // depth is the binary tree
     return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}

發佈了17 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章