[華為機試練習題]42.求二叉樹的深度和寬度,華為二叉樹

來源:互聯網
上載者:User

[華為機試練習題]42.求二叉樹的深度和寬度,華為二叉樹

題目

題目標題:

求二叉樹的寬度和深度給定一個二叉樹,擷取該二叉樹的寬度和深度。   例如輸入   a  / \ b   c/ \ / \d e f g返回3.

介面說明
原型:

     int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)

輸入參數:

     head   需要擷取深度的二叉樹頭結點

輸出參數(指標指向的記憶體地區保證有效):

     pulWidth   寬度     pulHeight  高度

傳回值:

     0          成功     1          失敗或其他異常

練習階段:

中級 

代碼

/*---------------------------------------*   日期:2015-07-03*   作者:SJF0115*   題目:求二叉樹的深度和寬度*   來源:華為機試練習題-----------------------------------------*/#include <iostream>#include "OJ.h"#include <string>#include <queue>using namespace std;/*Description           給定一個二叉樹,擷取該二叉樹的寬度深度。Prototype         int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)Input Param          head   需要擷取深度的二叉樹頭結點Output Param          pulWidth   寬度         pulHeight  高度Return Value         0          成功         1          失敗或其他異常*/int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight){    if(&head == NULL || pulWidth == NULL || pulHeight == NULL){        return 1;    }//if    int maxWidth = 0;    int curWidth = 0;    int height = 0;    BiNode* root = &head;    queue<BiNode*> curQueue;    queue<BiNode*> nextQueue;    curQueue.push(root);    // 層次遍曆    while(!curQueue.empty()){        ++height;        curWidth = 0;        while(!curQueue.empty()){            ++curWidth;            BiNode* node = curQueue.front();            curQueue.pop();            // 左子結點不為空白            if(node->left != NULL){                nextQueue.push(node->left);            }//if            // 右子節點不為空白            if(node->right != NULL){                nextQueue.push(node->right);            }//if        }//while        // 更新最大寬度        if(curWidth > maxWidth){            maxWidth = curWidth;        }//if        swap(curQueue,nextQueue);    }//while    *pulWidth = maxWidth;    *pulHeight = height;    return 0;}

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.