首页 > 其他 > 详细

求二叉树的深度和宽度 ----我对默认构造函数的理解

时间:2015-04-29 13:10:41      阅读:394      评论:0      收藏:0      [点我收藏+]

////计算二叉树的深度和宽度:深度:层数   宽度:各层最大节点数

///关于二叉树问题,一般都要用到递归的方法。

////算法:首先构造二叉树节点的结构;要创建二叉树,创建的过程,使用递归算法;其次,计算二叉树深度,也要递归;最难的一点是计算求出层次中的最大节点数,使用队列的方法

#include <iostream>
#include <queue>
#include <tchar.h>
using namespace std;
struct BTNode{
char m_value;
BTNode* m_left;
BTNode* m_right;

};

void CreateBtree(BTNode* &pRoot)
{
char nValue = 0;
cin>>nValue;
if(nValue == ‘#‘)
return;
/////注意啦!!!new BTNode()调用默认构造函数
///默认构造函数的作用是将结构体或class中的基本变量做初始化
//比如int类型初始化为0,string类型初始化"";指针类型初始化为NULL
///这一点非常重要,如果创建一个节点,其m_left和m_right别初始化为NULL
////一个节点是否为叶子节点就是通过判断其左右孩子是否为null来判断的
pRoot = new BTNode();
pRoot->m_value = nValue;
CreateBtree(pRoot->m_left);
CreateBtree(pRoot->m_right);
}

int GetDepth(BTNode* pRoot)
{
if(pRoot == NULL)
return 0;
int lLen = 0;
int rLen = 0;
lLen = GetDepth(pRoot->m_left);
rLen = GetDepth(pRoot->m_right);
return lLen > rLen ? lLen+1 : rLen+1;
}

int GetWidth(BTNode* pRoot)
{
if(pRoot == NULL)
return 0;
queue<BTNode*> que;
BTNode* pCur= NULL;
que.push(pRoot);
int iWidth= 1;
int iLastLen = 1;
int iCurLen =0;
int iTempLastLen = 0;
while(!que.empty())
{
iTempLastLen = iLastLen;
pCur = que.back();
que.pop();
while(iTempLastLen != 0)
{
if(pCur->m_left != NULL)
que.push(pCur->m_left);
if(pCur->m_right != NULL)
que.push(pCur->m_right);
iTempLastLen--;
}
iCurLen = que.size();
iWidth = iWidth > iCurLen ? iWidth : iCurLen;
iLastLen = iCurLen;
}
return iWidth;

}

int main()
{
BTNode *pRoot = NULL;
CreateBtree(pRoot);
int idepth = 0;
idepth = GetDepth(pRoot);
int iwidth = 0;
iwidth = GetWidth(pRoot);
cout <<idepth<< " "<<iwidth <<endl;
return 0;
}

 

求二叉树的深度和宽度 ----我对默认构造函数的理解

原文:http://www.cnblogs.com/niupan369/p/4465602.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!