码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的实现

时间:2016-05-02 08:15:32      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:二叉树

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;

二叉树的实现

标签:二叉树

原文地址:http://10738651.blog.51cto.com/10728651/1769394

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!