二叉树的基本操作
来源:互联网 发布:服务器监控软件 编辑:程序博客网 时间:2024/05/22 06:10
二叉树的实现:
#include<stdio.h>#include<queue>#include<stack>#include<list>#include<iostream>using namespace std;//二叉树节点template<class T>struct BinaryTreeNode{ BinaryTreeNode() :_pLeft(NULL) ,_pRight(NULL) {} T _data; BinaryTreeNode<T>* _pLeft; BinaryTreeNode<T>* _pRight;};//二叉树template<class T>class BinaryTree{public:typedef BinaryTreeNode<T> Node;private:Node* _pRoot;//根节点}
二叉树的基本操作:
- 二叉树的创建:
BinaryTree()//空二叉树的构造函数 :_pRoot(NULL) {} BinaryTree(const T arr[],size_t size,T& invalid)//带参数二叉树的构造函数,arr为前序遍历得到的一组序列 { size_t index = 0; }//封装的底层函数 _CreateBinaryTree(_pRoot,arr,size,index,invalid);//创建二叉树 } void _CreateBinaryTree(Node*& pRoot,const T arr[],size_t size,size_t& index,T& invalid)//创建二叉树 { if(arr==NULL || size<=0 || index<0 || index>size+2)//判断参数合法性 return; if(arr[index]!=invalid) { pRoot = new Node; pRoot->_data = arr[index]; _CreateBinaryTree(pRoot->_pLeft,arr,size,++index,invalid);//注意index是不断加一的,不能用index+1或者index++来替换++index,因为在回退的过程中index也会回退 _CreateBinaryTree(pRoot->_pRight,arr,size,++index,invalid);//同时也要注意index做参数要用引用接收,也是为了避免这个问题 }
- 二叉树的拷贝构造函数
BinaryTree(const BinaryTree<T> & t)//二叉树的拷贝构造函数 { _pRoot = _CopyBinaryTree(t._pRoot); }Node* _CopyBinaryTree(Node* pRoot)//拷贝二叉树 { Node* pCur = NULL; if(pRoot != NULL) { pCur = new Node; pCur->_data = pRoot->_data; pCur->_pLeft = _CopyBinaryTree(pRoot->_pLeft); pCur->_pRight = _CopyBinaryTree(pRoot->_pRight); } return pCur; }
- 二叉树的赋值运算符重载
BinaryTree<T>& operator=(const BinaryTree<T>& t)//二叉树的赋值运算符重载 { if(this != &t) { _DestoryBinaryTree(_pRoot);//先析构*this _pRoot = _CopyBinaryTree(t._pRoot);//再用t拷贝构造*this } return *this; }
- 二叉树的析构函数
~BinaryTree()//析构二叉树 { _DestoryBinaryTree(_pRoot); }void _DestoryBinaryTree(Node* &pRoot)//销毁二叉树(利用后序遍历,先删除左节点,再删除右节点,最后删除根节点) { if(pRoot != NULL) { _DestoryBinaryTree(pRoot->_pLeft); _DestoryBinaryTree(pRoot->_pRight); delete pRoot; pRoot = NULL; } }
0 0
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- 二叉树的基本操作
- python os.path模块常用方法详解
- 基于proteus的51单片机仿真实例五十七、定时器/计数器T0的定时实例
- 操作系统开发技术(Linux内核编译)-新系统调用设计实验
- 0430-div和span标签
- 热修复及lua脚本
- 二叉树的基本操作
- WebService开发
- HDU 2955 (01背包变形)
- 详解Java中super的几种用法并与this的区别
- Numpy练习100题--难度★☆☆
- 使用Python通过win32 COM接口实现Excel单元格写入
- 基于proteus的51单片机仿真实例五十八、定时器/计数器T1的定时实例
- CTF 图片相关
- After 486 blog posts