【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; }
相关文章推荐
- 邻接表-C++
- c++程序编码
- 【C++】两个栈实现一个队列
- 【C++】两个队列实现一个栈
- C++点滴
- C++学习第六课--引用
- GUN C/C++ __attribute__ 用法
- xcode中c++变量断点不显示
- C/C++——auto,static,register,extern用法
- C++11与Unicode及使用标准库进行UTF-8、UTF-16、UCS2、UCS4/UTF-32编码转换
- C++:位操作基础篇之位操作全面总结
- c语言关于时间的两个函数
- 学习笔记7-C语言预处理
- c++ 返回对象的引用要小心
- C++学习 (使用类)
- c语言文件IO库函数——APUE学习笔记(1)
- 魔方矩阵 C++实现
- C++ 二叉树的遍历
- C语言错误日志——指针返回值与数组
- C语言公式--爱情的年轮