/*对二叉树的操作主要通过递归实现,递归能把一个复杂的问题最大程度的简化。以前实现二叉树主要通过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);
}
void midShow(Node *root)
{
if(root == NULL)
{
return;
}
midShow(root->left);
cout<<root->data<<' ';
midShow(root->right);
}
void clearTree(Node *&root)
{
if(root == NULL) return;
Node *tree = root;
clearTree(root->left);
clearTree(root->right);
delete tree;
root = NULL;
}
int count(Node *&root)
{
if(root == NULL) return 0;
return count(root->left)+count(root->right)+1;
}
Node *& find(Node *&root,T value)
{
if(root == NULL) return root;
if(root->data == value) return root;
else if(value < root->data)
find(root->left,value);
else
find(root->right,value);
}
int height(Node *root)
{
if(root == NULL) return 0;
int lh,rh;
lh=height(root->left);
rh=height(root->right);
return (lh>=rh?lh:rh)+1;
}
};
#endif
/*===============测试代码================*/
// TreeTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "tree.h"
int main(int argc, char* argv[])
{
Tree<int> t;
t.add(18);
t.add(12);
t.add(26);
t.add(7);
t.add(16);
t.add(5);
t.add(8);
t.add(14);
t.add(17);
t.sortShow();
// t.remove(26);
// t.sortShow();
cout<<"the count is:"<<t.count()<<" the height:"<<t.height()<<endl;
return 0;
}
C++ 二叉树的描述
最新推荐文章于 2025-02-20 23:07:37 发布