【发布时间】:2019-01-19 13:08:48
【问题描述】:
我才刚刚开始学习数据结构,所以请原谅我的愚蠢,我正在尝试开发自己的 BST 版本,我不明白为什么需要父节点?这不应该很好吗。
class BST
{
private Node root;
public BST()
{
root = null;
}
public void insert(int value)
{
Node temp = new Node();
temp.value = value;
if (root == null)
{
root = temp;
return;
}
Node current = root;
while (current != null)
{
if (value <= current.value)
{
current = current.lc;
}
else
{
current = current.rc;
}
}
current = temp;
}
}
class Node
{
public Node lc;
public int value;
public Node rc;
}
肯定有一些东西我错过了,我无法掌握或得到它是什么,当 current 为空时,我们已经到了我们需要插入节点的位置,为什么我们需要一个父节点。
【问题讨论】:
-
“需要”是什么意思?
-
我无法正确理解您所缺少的是什么。能不能说的详细点?
-
Umm V0ldek,我不明白你...据我所知,我们需要一个节点来指向我们要插入的节点的父节点。
-
我为创建 BST 编写的上述代码对插入函数有效吗?
-
不,不是。
current = temp;没有任何用处,只是分配局部变量。为了进行实际插入,必须将temp分配给parent.lc或parent.rc。
标签: c# data-structures tree binary-search-tree