二叉搜索树可用来对n个元素进行排序。
答案:2 悬赏:30 手机版
解决时间 2021-01-30 01:19
- 提问者网友:战皆罪
- 2021-01-29 14:54
二叉搜索树可用来对n个元素进行排序。
最佳答案
- 五星知识达人网友:爱难随人意
- 2021-01-29 15:36
。。。楼下嫌分少的泥垢了,就是个search tree又不是bst,有啥麻烦的,分分钟的事情,java写一下,下面的代码没编译过,可能有bug,但基本就是这么个东西
class Node
{
int num;
Node l;
Node r;
Node(int val)
{
num = val; l = null; r = null;
}
}
public class xxx
{
static Node tree = null;
static int n;
static int[] a;
public static void addTree(Node tree, int val)
{
Node nowat = tree;
while (true)
{
if (val < nowat.num)
{
if (nowat.l == null)
{
nowat.l = new Node(val);
break;
}
else nowat = nowat.l;
}
else
{
if (nowat.r == null)
{
nowat.r = new Node(val);
break;
}
else nowat = nowat.r;
}
}
}
public static void traverse(Node nowat)
{
if (nowat.l != null) traverse(nowat.l);
System.out.println(nowat.num);
if (nowat.r != null) traverse(nowat.r);
}
public static void main()
{
// 输入你自己搞
if (n == 0) return;
tree = new Node(a[0]);
for (int i = 1; i < n; ++i)
addTree(tree, a[i]);
traverse(tree);
}
}
class Node
{
int num;
Node l;
Node r;
Node(int val)
{
num = val; l = null; r = null;
}
}
public class xxx
{
static Node tree = null;
static int n;
static int[] a;
public static void addTree(Node tree, int val)
{
Node nowat = tree;
while (true)
{
if (val < nowat.num)
{
if (nowat.l == null)
{
nowat.l = new Node(val);
break;
}
else nowat = nowat.l;
}
else
{
if (nowat.r == null)
{
nowat.r = new Node(val);
break;
}
else nowat = nowat.r;
}
}
}
public static void traverse(Node nowat)
{
if (nowat.l != null) traverse(nowat.l);
System.out.println(nowat.num);
if (nowat.r != null) traverse(nowat.r);
}
public static void main()
{
// 输入你自己搞
if (n == 0) return;
tree = new Node(a[0]);
for (int i = 1; i < n; ++i)
addTree(tree, a[i]);
traverse(tree);
}
}
全部回答
- 1楼网友:醉吻情书
- 2021-01-29 16:35
5分太少了
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯