[华为机试练习题]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* 题目:求二叉树的深度和宽度* 来源:华为机试练习题—————————————–*/;/*Description给定一个二叉树,获取该二叉树的宽度深度。Prototypeint GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight)Input Paramhead 需要获取深度的二叉树头结点Output ParampulWidth 宽度pulHeight 高度Return Value0成功1失败或其他异常*/*pulHeight){if(&head == NULL || pulWidth == NULL || pulHeight == NULL){return 1;}//ifint 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);}(node->right != NULL){nextQueue.push(node->right);}//if}(curWidth > maxWidth){maxWidth = curWidth;}//ifswap(curQueue,nextQueue);}//while*pulWidth = maxWidth;*pulHeight = height;return 0;}

蚁穴虽小,溃之千里。

[华为机试练习题]42.求二叉树的深度和宽度

相关文章:

你感兴趣的文章:

标签云: