C++ 二叉树的描述

/*对二叉树的操作主要通过递归实现,递归能把一个复杂的问题最大程度的简化。以前实现二叉树主要通过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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值