[编程之美-17]求二元树的度
来源:互联网 发布:淘宝账号违规怎么解封 编辑:程序博客网 时间:2024/06/05 15:19
题目:输入一棵二元树的根结点,求该树的深度。
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
例如:输入二元树:
8
/ /
6 10
// //
5 7 9 11
输出该树的深度3。
思想:同[编程之美-16]主要考察还是层序遍历思想。
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
例如:输入二元树:
8
/ /
6 10
// //
5 7 9 11
输出该树的深度3。
二元树的结点定义如下:
struct SBinaryTreeNode // a node of the binary tree{ int m_nValue; // value of node SBinaryTreeNode *m_pLeft; // left child of node SBinaryTreeNode *m_pRight; // right child of node};
思想:同[编程之美-16]主要考察还是层序遍历思想。
代码如下:
#include<iostream>#include<deque>using namespace std;struct BSTreeNode{ int m_nValue; BSTreeNode *m_pleft; BSTreeNode *m_pright;};int depthOfBSTree = 0;void addBSTreeNode(BSTreeNode *&pCurrent, int value);void levelOrderBSTree(BSTreeNode *pRoot);int main(){ BSTreeNode *pRoot = NULL; addBSTreeNode(pRoot, 8); addBSTreeNode(pRoot, 6); addBSTreeNode(pRoot, 5); addBSTreeNode(pRoot, 7); addBSTreeNode(pRoot, 10); addBSTreeNode(pRoot, 9); addBSTreeNode(pRoot, 11); levelOrderBSTree(pRoot); cout<<depthOfBSTree<<endl; return 0;}void levelOrderBSTree(BSTreeNode *pRoot){ if(pRoot == NULL) return ; deque<BSTreeNode*> que; que.push_back(pRoot); BSTreeNode *last, *nlast; last = pRoot; nlast = pRoot; while(que.size() != 0) { BSTreeNode *pCurrent = que.front(); que.pop_front(); if(pCurrent->m_pleft != NULL) { nlast = pCurrent->m_pleft; que.push_back(pCurrent->m_pleft); } if(pCurrent->m_pright != NULL) { nlast = pCurrent->m_pright; que.push_back(pCurrent->m_pright); } if(pCurrent == last) { depthOfBSTree ++; last = nlast; } }}void addBSTreeNode(BSTreeNode *&pCurrent, int value){ if(pCurrent == NULL) { BSTreeNode *pBSTree = new BSTreeNode(); pBSTree->m_nValue = value; pBSTree->m_pleft = NULL; pBSTree->m_pright = NULL; pCurrent = pBSTree; } else { if((pCurrent->m_nValue) > value) addBSTreeNode(pCurrent->m_pleft, value); else if((pCurrent->m_nValue) < value) addBSTreeNode(pCurrent->m_pright, value); }}
阅读全文
0 0
- [编程之美-17]求二元树的度
- [编程之美-08]求二元树的度
- [编程之美-02]把二元查找树变成为排序的双向链表
- [编程之美-03]在二元树中找出和为某一值的所有路径
- [编程之美-11]把二元查找树变成为排序的双向链表
- [编程之美-12]在二元树中找出和为某一值的所有路径
- 编程之美 - 求二叉树节点的最大距离
- 编程之美---求1的数目
- 编程之美---求1的数目
- [编程之美-06]输入一颗二元查找树将该树转换为它的镜像
- [编程之美-15]输入一颗二元查找树将该树转换为它的镜像
- [编程之美-04]判断整数序列是不是二元查找数的后序遍历结果
- [编程之美-13]判断整数序列是不是二元查找数的后序遍历结果
- 求二元树的深度
- 求二元树的深度
- 【编程之美】求最大公约数
- [编程之美-07]层序打印二元树,每层打印一行
- [编程之美-16]层序打印二元树,每层打印一行
- FZU 2278 期望
- 文章标题
- Java之List和Map的几种遍历方式
- Spring学习(三)
- DOM创建节点及节点属性
- [编程之美-17]求二元树的度
- ajax技术知识梳理与总结
- CodeForces
- 树状数组应用汇总(全)
- 实战详解win10专业版/企业版升级到win10 Enterprise G 企业政府版教程
- 【Android API】startActivity流程分析
- 1015. 德才论 (25)
- 【哈夫曼树,贪心】BZOJ4198 [Noi2015]荷马史诗
- Java学习笔记(三)——文件读写操作