您的位置:首页 > 编程语言 > C语言/C++

复习笔记二 二叉排序树(C++ C#)

2007-12-24 19:41 489 查看
C++ 版
#include"iostream.h"
#include"string.h"

class node //节点类
{
public:
int data;
node *l;
node *r;
node(int p_data);
node(node *p_node);
};

node::node(int p_data)
{
data=p_data;
l=NULL;
r=NULL;
}

node::node(node *p_node) //拷贝构造
{
data=p_node->data;
l=p_node->l;
r=p_node->r;
}

class btree //二叉树
{
public:
node *Root; //根
btree(){Root=NULL;}
node add(node *p,int p_data);//构造二叉排序树
void display(node *p);
node add(int p_data);

};

node btree::add(int p_data)
{
if(Root==NULL)
{
Root=new node(p_data);
}
else
{
add(Root,p_data);
}
return *Root;
}

node btree::add(node *p,int p_data)
{
if(p==NULL)
{
p=new node(p_data);
}
else if(p_data<p->data)
{
p->l=new node(add(p->l,p_data));
}
else
{
p->r=new node(add(p->r,p_data));
}
return *p;
}

void btree::display(node *p)
{
cout<<"***********"<<endl;
if(p==NULL)
return;
else
{
display(p->l);
cout<<p->data<<endl;
display(p->r);
}
}

void main()
{
btree mybtree;
int a;
cin>>a;
for(int i=0;i<a;i++)
{
int data;
cin>>data;
mybtree.add(mybtree.Root,data);
}
mybtree.display(mybtree.Root);
}

C#版

//Program.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace 二叉排序树
{
class Program
{
static void Main(string[] args)
{
Node n = null;
tree mytree = new tree();
int p = int.Parse(Console.ReadLine());
for (int i = 0; i < p; i++)
{
int data = int.Parse(Console.ReadLine());
n = mytree.Add(n, data);
}
mytree.display(n);
Console.ReadLine();
}
}
}
//Node.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace 二叉排序树
{
public class Node
{
public Node Left = null;
public Node Right = null;
public int Data;
public Node(int data)
{
Data = data;
}
}
}

//tree.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace 二叉排序树
{
public class tree
{
public Node Add(Node p, int p_data)
{
if (p == null)
{
p = new Node(p_data);
}
else
{
if (p_data < p.Data)
{
p.Left = Add(p.Left, p_data);
}
else
{
p.Right = Add(p.Right, p_data);
}
}
return p; ;
}

public void display(Node h)
{
Console.WriteLine("****");
while (h != null)
{
Console.WriteLine(h.Data.ToString());
h = h.Left;
}
}
}
}

文章引用自:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: