二叉树的C++描述
来源:优易学  2011-12-11 16:19:00   【优易学:中国教育考试门户网】   资料下载   IT书店

  /*对二叉树的操作主要通过递归实现,递归能把一个复杂的问题最大程度的简化。以前实现二叉树主要通过C语言实现的,现在正在学习CORE C++,故决定用C++重新实现...*/

  #ifndef _TREE_H_

  #define _TREE_H_

  #include <iostream>

  using namespace std;

  template <typename T> class Tree //binary sort tree

  {

  struct Node

  {

  T data;

  Node *left;

  Node *right;

  };

  Node *root;

  public:

  Tree():root(NULL){};

  void add(T value)//add element to tree

  {

  Node *n = new Node;

  n->data = value;

  n->left = NULL;

  n->right = NULL;

  insert(root,n);

  }

  void show(){ preShow(root); cout<<endl;};//preorder search

  void sortShow(){ midShow(root); cout<<endl;};//midorder search

  void clear(){ clearTree(root);};//clear the tree

  int count(){//calculate the node's count of tree

  return count(root);

  }

  int height(){ return height(root); } //calculate height of tree

  void remove(T value)//remove a element from tree

  {

  Node *&n = find(root,value);

  Node *p = n;

  if(n == NULL) return;

  insert(n->right,n->left);

  n = n->right;

  delete p;

  }

  ~Tree()

  {

  clear();

  }

  private:

  void insert(Node *&root,Node *&d)

  {

  if(root == NULL) root = d;

  else if(d->data < root->data)

  insert(root->left,d);

  else

  insert(root->right,d);

  }

  void preShow(Node *root)

  {

  if(root == NULL)

  {

  return;

  }

  cout<<root->data<<' ';

  preShow(root->left);

  preShow(root->right);

  }

[1] [2] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训