[華為機試練習題]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;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。