二叉树
2016-04-20 17:45
363 查看
二叉树:
二叉树是一棵特殊的树,二叉树每个节点最多有两个孩子结点,分别称为左孩子和右孩子。
实例:
节点结构:
二叉树是一棵特殊的树,二叉树每个节点最多有两个孩子结点,分别称为左孩子和右孩子。
实例:
节点结构:
template <class T> struct BinaryTreeNode { BinaryTreeNode(T data) :_data(data) ,_left(NULL) ,_right(NULL) {} T _data; BinaryTreeNode<T>* _left; BinaryTreeNode<T>* _right; };二叉树成员变量;
protected: BinaryTreeNode<T>* _root;构造函数:调用_CreateTree
Node* _CreateTree(const T* a,size_t size,size_t& index,const T& invalid)//注意index用引用 { Node* root=NULL; if((index<size)&&(a[index]!=invalid)) { root=new Node(a[index]); root->_left=_CreateTree(a,size,++index,invalid); root->_right=_CreateTree(a,size,++index,invalid); } return root; }析构函数:调用_Destory
void _Destory(Node* root) { Node* cur=root; Node* del=cur; if(cur->_left!=NULL) { _Destory(cur->_left); } if(cur->_right!=NULL) { _Destory(cur->_right); } delete del; }拷贝构造函数:调用_Copy
Node* _Copy(Node* root) { if(root==NULL) return NULL; Node* newroot=new Node(root->_data); Node* cur=newroot; cur->_left=_Copy(root->_left); cur->_right=_Copy(root->_right); return newroot; }重载赋值运算符
BinaryTree& operator=(BinaryTree tree) { swap(_root,tree._root); return *this; }前序遍历:调用_PrevOrder
void _PrevOrder(Node* root) { if(root==NULL) return; cout<<root->_data<<" "; _PrevOrder(root->_left); _PrevOrder(root->_right); }中序遍历:调用_InOrder
void _InOrder(Node* root) { if(root==NULL) return; _InOrder(root->_left); cout<<root->_data<<" "; _InOrder(root->_right); }后序遍历:调用_PoseOrder
void _PostOrder(Node* root) { if(root==NULL) return; _PostOrder(root->_left); _PostOrder(root->_right); cout<<root->_data<<" "; }求深度:调用_Depth
size_t _Depth(Node* root) { Node* cur=root; size_t depth=0; if(cur==NULL) return 0; else { depth=1; size_t leftdepth=_Depth(cur->_left); size_t rightdepth=_Depth(cur->_right); if(leftdepth>=rightdepth) { return depth+leftdepth; } else { return depth+rightdepth; } } }求size:调用_Size
size_t _Size(Node* root) { size_t count=0; if(root==NULL) return 0; else { ++count; } count+=_Size(root->_left); count+=_Size(root->_right); return count; }求叶子节点的个数:调用_LeafSize
size_t _LeafSize(Node* root) { size_t size=0; if(root==NULL) return 0; else { if((root->_left==NULL)&&(root->_right==NULL)) { size=1; return size; } else { size_t left=_LeafSize(root->_left); size_t right=_LeafSize(root->_right); return left+right; } } }
相关文章推荐
- HDU 1907 John
- android多线程并发协调semaphore机制
- Spring HTTP Invoker使用介绍
- hiho 42 骨牌覆盖问题·二
- JSP杂项知识
- HTML DOM 属性
- 编译原理 词法分析
- JS性能优化笔记
- “并发用户数”、“系统用户数”和“同时在线用户数”的计算公式
- android开发 根据上传图片张数变换不同的布局
- iftop监控网卡,ip流量
- Sublime text 3 最新版 注册码 破解
- Configure,Makefile.am, Makefile.in, Makefile文件之间关系
- 取硬币问题
- c++11 线程池
- JDK容器与并发—并发
- LeetCode *** 92. Reverse Linked List II
- Linux Grub系统加密、破密、修复
- JDK容器与并发—Queue—LinkedBlockingQueue
- centos+zabbix(基于lamp)