二叉树的实现

发布时间:2020-07-21 23:51:42 作者:hhaxy77
来源:网络 阅读:275

BinaryTree.h

#pragma once
template <class T>
struct BinaryTreeNode
{
 BinaryTreeNode<T>* _right;
 BinaryTreeNode<T>* _left;
 T _data;
 BinaryTreeNode(const T& d)
  :_right(NULL)
  ,_left(NULL)
  ,_data(d)
 {}
};
template <class T>
class BinaryTree
{
 typedef BinaryTreeNode<T> Node;
public:
 BinaryTree()
  :_root(NULL)
 {}
 BinaryTree(const T* a, size_t size, const T& invalid)
 {
  size_t index = 0;
  _root = _CreatTree(a, size, index, invalid);
 }
 BinaryTree(const BinaryTree<T>& t)
 {
  _root = _CopyTree(t._root);
 }
 ~BinaryTree()
 {
  _Destory(_root);
  _root = NULL;
 }
 size_t Size()      //求二叉树结点数目
 {
  return _Size(_root);
 }
 size_t Depth()    //求二叉树深度
 {
  return _Depth(_root);
 }
 void PrevOrder()   //前序遍历
 {
  _PrevOrder(_root);
  cout<<endl;
 }
protected:
 Node* _CreatTree(const T* a, size_t size, size_t& index, const T& invalid)
 {
  Node* root = NULL;
  if(index<size && a[index]!=invalid)
  {
   root = new Node(a[index]);
   root->_left = _CreatTree(a, size, ++index, invalid);
   root->_right = _CreatTree(a, size, ++index, invalid);
  }
  return root;
 }
 Node* _CopyTree(const Node* root)
 {
  if(root == NULL)
  {
   return NULL;
  }
  Node* newRoot = new Node(root->_data);
  newRoot->_left = _CopyTree(root->_left);
  newRoot->_right = _CopyTree(root->_right);
  return newRoot;
 }
 void _Destory(Node* root)
 {
  if(root == NULL)
  {
   return;
  }
  _Destory(root->_left);
  _Destory(root->_right);
  delete root;
 }
 size_t _Size(Node* root)    
 {
  if(root == NULL)
  {
   return 0;
  }
  return _Size(root->_left)+_Size(root->_right)+1;
 }
 size_t _Depth(Node* root)
 {
  if(root == NULL)
  {
   return 0;
  }
  size_t leftDepth = _Depth(root->_left);
  size_t rightDepth = _Depth(root->_right);
  return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;
 }
 void _PrevOrder(Node* root)
 {
  if(root == NULL)
  {
   return;
  }
  cout<<root->_data<<",";
  _PrevOrder(root->_left);
  _PrevOrder(root->_right);
 }
private:
 Node* _root;

推荐阅读:
  1. 二叉树的非递归实现
  2. 二叉树的递归实现

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

二叉树

上一篇:Android 隐藏软键盘

下一篇:MSSQL创建维护计划自动备份数据库

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》