using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication5
{
class BSTree
{
public class node
{
public int key;
public sbyte data;
public node lchild;
public node rchild;
}
internal static class DefineConstantsBSTree
{
public const int MaxSize = 100;
}
public static class GlobalMembersBSTree
{
public static int[] path = new int[DefineConstantsBSTree.MaxSize];
public static void DispBST(node bt)
{
if (bt!=null)
{
Console.Write("{0:D}",bt.key);
if (bt.lchild!=null || bt.rchild!=null)
{
Console.Write("(");
DispBST(bt.lchild);
if (bt.rchild!=null)
Console.Write(",");
DispBST(bt.rchild);
Console.Write(")");
}
}
}
public static int InsertBST(ref node p, int k)
{
if (p == null)
{
p.key = k;
p.lchild = p.rchild = null;
return 1;
}
else if (k == p.key)
return 0;
else if (k<p.key)
return InsertBST(ref p.lchild, k);
else
return InsertBST(ref p.rchild, k);
}
public static node CreatBST(int[] A, int n)
{
node bt = null;
int i = 0;
while (i<n)
InsertBST(ref bt, A[i++]);
return bt;
}
public static int SearchBST(node bt, int k, int[] path, int i)
{
if (bt == null)
return i;
else if (k == bt.key)
{
path[i+1] =bt.key;
return i+1;
}
else
{
path[i+1] =bt.key;
if (k<bt.key)
return SearchBST(bt.lchild, k, path, i+1);
else
return SearchBST(bt.rchild, k, path, i+1);
}
}
public static void SearchResult(node bt, int k1)
{
int r;
int j;
r = SearchBST(bt, k1, path, -1);
for (j = 0; j<=r; j++)
Console.Write("{0,3:D}",path[j]);
Console.Write("\n");
}
internal static int Main()
{
node bt;
int k1 = 65;
int k2 = 32;
int[] a = {43,91,10,18,82,65,33,59,27,73};
int n = 10;
Console.Write("创建的BST树:");
bt = CreatBST(a, n);
DispBST(bt);
Console.Write("\n");
Console.Write(" 查找{0:D}关键字:",k1);
SearchResult(bt, k1);
Console.Write(" 查找{0:D}关键字:",k2);
SearchResult(bt, k2);
return 0;
}
}
}
}
CreatBST(int[] A, int n)的方法里
while (i<n)
InsertBST(ref bt, A[i++]);
数组下标越界了,这样改一下
while (i<n)
InsertBST(ref bt, A[++i]);
你不是逗么,if(n==NULL){n.k}不错才见鬼呢,如果为NULL的时候n=new test()
p这个对象都为null了,你怎么还能使用它调用成员呢
(╯з╰)不好意思我回答错了,看岔了,确实是p == null的问题
应该是p!=null吧,哪里抄的程序。。。。。。。。。。。。。。