[Huawei machine trial exercise] 42. Calculate the depth and width of binary tree.
Question
Title:
Calculate the width and depth of a binary tree, and obtain the width and depth of the binary tree. For example, input a/\ B c/\ d e f g, and 3 is returned.
Interface Description
Prototype:
int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)
Input parameters:
Head needs to obtain the depth of the binary tree head node
Output Parameters (the memory area pointed to by the pointer is valid ):
PulWidth width pulHeight height
Return Value:
0 Success 1 failure or other exceptions
Exercise phase:
Intermediate
Code
/* ------------------------------------- * Date: 2015-07-03 * Author: SJF0115 * question: finding the depth and width of a binary tree * Source: Huawei machine trial exercise subject */# include <iostream> # include "OJ. h "# include <string >#include <queue> using namespace std;/* Description specifies a binary tree to obtain the width and depth of the binary tree. Prototype int GetBiNodeInfo (BiNode & head, unsigned int * pulWidth, unsigned int * pulHeight) input Param head needs to obtain the depth of the binary tree head node Output Param pulWidth width pulHeight Return Value 0 Success 1 failure or other exceptions */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; BiNod E * root = & head; queue <BiNode *> curQueue; queue <BiNode *> nextQueue; curQueue. push (root); // traverse the while (! CurQueue. empty () {++ height; curWidth = 0; while (! CurQueue. empty () {++ curWidth; BiNode * node = curQueue. front (); curQueue. pop (); // The left subnode is not empty if (node-> left! = NULL) {nextQueue. push (node-> left);} // if // The right subnode is not empty if (node-> right! = NULL) {nextQueue. push (node-> right);} // if} // while // update the maximum width if (curWidth> maxWidth) {maxWidth = curWidth;} // if swap (curQueue, nextQueue);} // while * pulWidth = maxWidth; * pulHeight = height; return 0 ;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.