面試題:二叉樹的深度

來源:互聯網
上載者:User
題目:輸入一棵二叉樹的根節點,求該樹的深度。從根節點到葉子結點一次經過的結點形成樹的一條路徑,最長路徑的長度為樹的深度。根節點的深度為1。

解體思路:

  1. 如果根節點為空白,則深度為0,返回0,遞迴的出口
  2. 如果根節點不為空白,那麼深度至少為1,然後我們求他們左右子樹的深度,
  3. 比較左右子樹深度值,返回較大的那一個
  4. 通過遞迴調用

代碼實現

View Code

#include<iostream>#include<stdlib.h>using namespace std;struct BinaryTreeNode{    int m_nValue;    BinaryTreeNode* m_pLeft;    BinaryTreeNode* m_pRight;};//建立二叉樹結點BinaryTreeNode* CreateBinaryTreeNode(int value){    BinaryTreeNode* pNode=new BinaryTreeNode();    pNode->m_nValue=value;    pNode->m_pLeft=NULL;    pNode->m_pRight=NULL;    return pNode;}//串連二叉樹結點void ConnectTreeNodes(BinaryTreeNode* pParent,BinaryTreeNode* pLeft,BinaryTreeNode* pRight){    if(pParent!=NULL)    {        pParent->m_pLeft=pLeft;        pParent->m_pRight=pRight;    }}//求二叉樹深度int TreeDepth(BinaryTreeNode* pRoot)//計算二叉樹深度{    if(pRoot==NULL)//如果pRoot為NULL,則深度為0,這也是遞迴的返回條件        return 0;    //如果pRoot不為NULL,那麼深度至少為1,所以left和right=1    int left=1;    int right=1;    left+=TreeDepth(pRoot->m_pLeft);//求出左子樹的深度    right+=TreeDepth(pRoot->m_pRight);//求出右子樹深度    return left>right?left:right;//返回深度較大的那一個}void main(){//            1//         /      \//        2        3//       /\         \//      4  5         6//           ///        7    //建立樹結點    BinaryTreeNode* pNode1 = CreateBinaryTreeNode(1);    BinaryTreeNode* pNode2 = CreateBinaryTreeNode(2);    BinaryTreeNode* pNode3 = CreateBinaryTreeNode(3);    BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);    BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);    BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);    BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);    //串連樹結點    ConnectTreeNodes(pNode1, pNode2, pNode3);    ConnectTreeNodes(pNode2, pNode4, pNode5);    ConnectTreeNodes(pNode3, NULL,   pNode6);    ConnectTreeNodes(pNode5, pNode7,  NULL );    int depth=TreeDepth(pNode1);    cout<<depth<<endl;    system("pause");}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.