设为首页 加入收藏

TOP

二叉树代码(较全) (四)
2014-11-23 21:42:24 来源: 作者: 【 】 浏览:15
Tags:代码 较全
ghtDepth = 0;

if(tree != NULL)
{
leftDepth = 1;
leftDepth += CaculateDepth(tree->leftChild);

rightDepth = 1;
rightDepth += CaculateDepth(tree->rightChild);
}

return leftDepth > rightDepth leftDepth : rightDepth;
}

//******************************************************************************
// Name: CaculateWidth
// Desc: 计算二叉树的宽度
//******************************************************************************
int CaculateWidth(Node* tree)
{
if (tree == NULL)
{
return 0;
}

typedef list QueueNode;
QueueNode queue;
unsigned int width = 0;
queue.push_back(tree);

while (queue.size() > 0)
{
unsigned int size = queue.size();

for (unsigned int i = 0; i < size; ++i) // 上一层的节点全部出列,并压入下一层节点
{
Node* curNode = queue.front();
queue.pop_front();

if (curNode->leftChild != NULL)
{
queue.push_back(curNode->leftChild);
}

if (curNode->rightChild != NULL)
{
queue.push_back(curNode->rightChild);
}

}
width = max(width, size); // 与每一个size比较,取最大者
}

return width;
}

//******************************************************************************
// Name: Release
// Desc: 释放资源
//******************************************************************************
void Release(Node* tree)
{
if(tree != NULL)
{
Release(tree->leftChild);
Release(tree->rightChild);
delete tree;
tree = NULL;
}
}


int main()

{
// 数据输入
vector dataVec;
int tempValue;
cout<<"请输入二叉树的先序扩展序列(-1为空):"< while(cin>>tempValue)
{
dataVec.push_back(tempValue);
}

// 二叉树的创建
Node* root = NULL;
root = CreateTree(root, dataVec);

// 二叉显示
DisplayTree(root);

// 递归先根遍历
FirstVisite(root);
cout<

// 递归中根遍历
CenterVisite(root);
cout<

// 递归后根遍历
AfterVisite(root);
cout<

cout<<"----------------------------"<

// 非递归先根遍历
_FirstVisite(root);
cout<

// 非递归先根遍历二
__FirstVisite(root);
cout<

// 非递归中根遍历
_CenterVisite(root);
cout<

// 非递归中根遍历思路二
__CenterVisite(root);
cout<

// 非递归后根遍历
_AfterVisite(root);
cout<

// 非递归后根遍历思路二
__AfterVisite(root);
cout<

// 层次遍历
LevelVisite(root);
cout<

// 计算叶子节点数量
cout<

// 计算所有节点数量
cout<

// 计算二叉树深度
cout<

// 计算二叉树宽度
cout<

// 释放资源
Release(root);

system("pause");
return 0;
}

\

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++一些注意点之操作符重载 下一篇poj2354

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·一篇说人话的文章, (2025-12-27 07:50:09)
·Python Web框架哪家 (2025-12-27 07:50:06)
·基于Python的数据分 (2025-12-27 07:50:03)
·深入理解 Java 集合 (2025-12-27 07:22:48)
·Java集合框架全面解 (2025-12-27 07:22:45)