递归实现二叉树

对于二叉树的实现主要运用递归进行实现,代码如下:

创新互联公司专注于昌吉企业网站建设,成都响应式网站建设,商城网站开发。昌吉网站建设公司,为昌吉等地区提供建站服务。全流程按需网站设计,专业设计,全程项目跟踪,创新互联公司专业和态度为您提供的服务

#include

template

struct BinaryTreeNode

{

T _data;

BinaryTreeNode *_left;

BinaryTreeNode *_right;

BinaryTreeNode(const T&x)

:_data(x)

, _left(NULL)

, _right(NULL)

{}

};

template

class BinaryTree

{

protected:

BinaryTreeNode *_root;

BinaryTreeNode *_creattree(const T a[], size_t size, size_t &index, T invalid)

{

BinaryTreeNode * root = NULL;

if (index < size && a[index] != invalid)

{

root = new BinaryTreeNode(a[index]);

root->_left = _creattree(a, size, ++index, invalid);

root->_right = _creattree(a, size, ++index, invalid);

}

return root;

}

void _prevorder(const BinaryTreeNode *root)

{

if (root == NULL)

return;

cout << root->_data << " ";

_prevorder(root->_left);

_prevorder(root->_right);*/

}

void _inorder(const BinaryTreeNode *root)

{

if (root == NULL)

return;

_inorder(root->_left);

cout << root->_data<<" ";

_inorder(root->_right);

}

void _postorder(const BinaryTreeNode *root)

{

if (root == NULL)

return;

_postorder(root->_left);

_postorder(root->_right);

cout << root->_data << " ";

}

size_t  _leafsize(const BinaryTreeNode *root)

{

if (root == NULL)

return 0;

if (root->_left == NULL && root->_right == NULL)

return 1;

return _leafsize(root->_left) + _leafsize(root->_right);

}

size_t _size(const BinaryTreeNode *root)

{

if (root == NULL)

return 0;

return _size(root->_left) + _size(root->_right) + 1;

}

size_t _Depth(const BinaryTreeNode *root)

{

if (root == NULL)

return 0;

int left = _Depth(root->_left);

int right = _Depth(root->_right);

return left > right ? left + 1 : right + 1;

}

public:

BinaryTree(T const*a = "", size_t size = 0)

{

size_t index = 0;

_root = _creattree(a, size, index, '#');

}

void prevorder()

{

_prevorder(_root);

}

void inorder()

{

_inorder(_root);

}

void postorder()

{

_postorder(_root);

}

size_t size()

{

int count = _size(_root);

return count;

}

size_t leafsize()

{

int count = _leafsize(_root);

return count;

}

size_t Depth()

{

int depth = _Depth(_root);

return depth;

}

};

void test()

{

BinaryTree b("12#3##45#6#7##8", 15);

/*b.levelorder();*/

/*BinaryTree b1;

b1 = b;*/

/*cout<

/*cout << b.size();*/

b.postorder();

/*cout << b.leafsize();*/

}

int main()

{

test();

getchar();

return 0;

}


新闻标题:递归实现二叉树
路径分享:http://hxwzsj.com/article/joospp.html

其他资讯

Copyright © 2025 青羊区翔捷宏鑫字牌设计制作工作室(个体工商户) All Rights Reserved 蜀ICP备2025123194号-14
友情链接: 成都网站设计 移动网站建设 重庆企业网站建设 古蔺网站建设 网站建设方案 成都定制网站建设 温江网站设计 成都网站建设推广 网站制作 重庆手机网站建设 定制网站建设多少钱 达州网站设计 网站建设开发 高端网站建设 成都网站制作 app网站建设 成都网站建设 成都响应式网站建设公司 成都品牌网站设计 教育网站设计方案 重庆网站设计 成都商城网站建设