您的位置:首页 > 编程语言 > C语言/C++

【C++】二叉树的基本操作

2015-11-19 21:06 169 查看






<pre name="code" class="cpp">#include<iostream>
#include<queue>
#include<stack>
using namespace std;
struct BinaryTreeNode
{
char _value;          //节点值
BinaryTreeNode*_left; //左孩子
BinaryTreeNode*_right;//右孩子
BinaryTreeNode(const char value)
:_value(value)
,_left(NULL)
, _right(NULL)
{}
};
class BinaryTree
{
public:
BinaryTree(const char *str)
:_root(NULL)
{
_CreatBinaryTree(_root, str);
}
//先序遍历
void RootSort()
{
cout << "先序遍历:" << endl;
_RootSort(_root);
cout << endl;
}
//中序遍历
void MidSort()
{
cout << "中序遍历:" << endl;
_MidSort(_root);
cout << endl;
}
//后序遍历
void BackSort()
{
cout << "后序遍历:" << endl;
_BackSort(_root);
cout << endl;
}

//层序遍历
//思想:队列的先进先出
void LevelSort()
{
cout << "层序遍历:" << endl;
queue<BinaryTreeNode*>q;
if (_root)
{
q.push(_root);
}
while (!q.empty())
{
BinaryTreeNode*front = q.front();
q.pop();
cout << front->_value << " ";
if (front->_left)
{
q.push(front->_left);
}
if (front->_right)
{
q.push(front->_right);
}
}
cout << endl;
}
//节点个数
int Size()
{
cout << "节点个数为:";
return _Size(_root);
}
int Depth()
{
cout << "二叉树深度为:";
return _Depth(_root);
}
protected:
void _CreatBinaryTree(BinaryTreeNode*&root, const char*&str)
{
if (*str != '#'&&*str != '\0')
{
root = new BinaryTreeNode(*str);
_CreatBinaryTree(root->_left, ++str);
if (*str != '\0')
{
_CreatBinaryTree(root->_right, ++str);
}
}
}
void _RootSort(BinaryTreeNode*&root)
{
if (root)
{
cout << root->_value << " ";
_RootSort(root->_left);
_RootSort(root->_right);
}
}
void _MidSort(BinaryTreeNode*&root)
{
if (root)
{
_MidSort(root->_left);
cout << root->_value << " ";
_MidSort(root->_right);
}
}
void _BackSort(BinaryTreeNode*&root)
{
if (root)
{
_BackSort(root->_left);
_BackSort(root->_right);
cout << root->_value << " ";
}
}
int _Size(BinaryTreeNode*&root)
{
if (root==NULL)
{
return 0;
}
else
{
return 1 + _Size(root->_left) + _Size(root->_right);
}
}
int _Depth(BinaryTreeNode*&root)
{
if (root == NULL)
{
return 0;
}
if (root->_left == NULL&&root->_right == NULL)
{
return 1;
}
return 1 + (_Depth(root->_left) > _Depth(root->_right)
? _Depth(root->_left) : _Depth(root->_right));
}
private:
BinaryTreeNode*_root;
};
void Test()
{
BinaryTree bt1("123##4##5678");
bt1.RootSort();
bt1.MidSort();
bt1.BackSort();
bt1.LevelSort();
cout << bt1.Size() << endl;
cout << bt1.Depth() << endl;
}
int main()
{
Test();
system("pause");
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: