二叉树是常用的数据结构,一个变形就是二叉查找树。二叉树有点像堆,如果二叉树是满二叉树,可以像堆一样用数组表示,否则就很浪费内存。二叉树常用链式表示:
struct Node{
Node(int d):data(d),left(NULL),right(NULL){}
int data;
Node *left;
Node *right;
};
可以用一个类来管理二叉树:
//二叉树类
class BinTree{
public:
BinTree():root(NULL){}
void createtree(int *p,int n);//建树,用数建树
void preoeder(Node *r,void (*visit)(int data)) ;//先序遍历
void inorder(Node *r,void (*visit)(int data)) ;//先序遍历
void postoeder(Node *r,void (*visit)(int data)) ;//先序遍历
int getdepth(Node *root);//获取树的深度
Node *getroot(){
return root;
}
void destroy(Node *root);
private:
Node *root;
};
//建二叉树,按照层次来建
void BinTree::createtree(int *p,int n)
{
queue<Node*> Q;
root=new Node(p[0]);
Q.push(root);
for(int i=1; i<n; i++)
{
Node *r=Q.front();
Q.pop();
r->left=new Node(p[i]);
Q.push(r->left);
i++;
if(i<n)
r->right=new Node(p[i]);
Q.push(r->right);
}
}
//先序遍历
void BinTree::preoeder(Node *r,void (*visit)(int data))
{
if(r==NULL) return;
visit(r->data);
preoeder(r->left,visit);
preoeder(r->right,visit);
}
//中序遍历
void BinTree::inorder(Node *r,void (*visit)(int data))
{
if(r==NULL) return;
inorder(r->left,visit);
visit(r->data);
inorder(r->right,visit);
}
//后序遍历
void BinTree::postoeder(Node *r,void(*visit)(int data))
{
if(r==NULL) return;
postoeder(r->left,visit);
postoeder(r->right,visit);
visit(r->data);
}
//获取树的深度
int BinTree::getdepth(Node *r)
{
int leftdepth=0;
int rightdepth=0;
if(r==NULL)
return 0;
leftdepth=getdepth(r->left);
rightdepth=getdepth(r->right);
return (leftdepth>rightdepth?leftdepth:rightdepth)+1;
}
//销毁树
void BinTree::destroy(Node *r)
{
if(r==NULL)
return;
destroy(r->left);
destroy(r->right);
delete r;
r=NULL;
}
测试类的代码:
#include<iostream>
#include<queue>
using namespace std;
//访问二叉树结点
void visit(int data)
{
cout<<data;
}
int main()
{
int n[]={1,2,3,4,5,6,7,8,9,10};
BinTree tree;
tree.createtree(n,10);
cout<<"preorder:";
tree.preoeder(tree.getroot(),visit);
cout<<endl<<"inorder:";
tree.inorder(tree.getroot(),visit);
cout<<endl<<"postorder:";
tree.postoeder(tree.getroot(),visit);
cout<<endl;
cout<<"depth:"<<tree.getdepth(tree.getroot())<<endl;
tree.destroy(tree.getroot());
return 0;
}