【发布时间】:2016-06-05 15:55:40
【问题描述】:
我能够编写自己的二叉搜索树,但在弄清楚如何将其转换为平衡二叉搜索树时遇到了很多麻烦。
谁能帮我用常规二叉树实现平衡二叉搜索树代码。
我认为我成功地更改了我的 TreeNode 类以进行必要的更改。
当您到达树中的第 3 个节点时,我添加了另一个键和另一个值以及另一个 TreeNode 中间来保存中间指针。
然后我添加了另一个构造函数来保存案例,如果它是一个 3 节点。我相信我做对了。
public class TreeNode<V>
{
public int key;
public int key1;
public V value;
public V value1;
public TreeNode<V> left;
public TreeNode<V> right;
public TreeNode<V> middle;
public TreeNode(int key, V value)
{
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
public TreeNode(int key, V value, int key1, V value1)
{
this.key = key;
this.key1 = key1;
this.value = value;
this.value1 = value1;
this.left = null;
this.right = null;
this.middle = null;
}
当我需要更改实际的 BST 类时,困难的部分就出现了。我知道 put 会发生很大变化,因为我们必须检查它是 2 节点还是 3 节点,以及检查父节点是什么。
这是我目前所拥有的:
public class BST<V>
{
private TreeNode<V> root;
public BST()
{
this.root = null;
}
public V get(int key)
{
return get(root, key);
}
private V get(TreeNode<V> current, int key)
{
if (current == null)
return null;
else if (key == current.key)
return current.value;
else if (key < current.key)
return get(current.left, key);
else
return get(current.right, key);
}
public void put(int key, V value)
{
if (root == null)
root = new TreeNode<>(key, value);
else
put(root, key, value);
}
private void put(TreeNode<V> current, int key, V value)
{
if (key == current.key)
{
current.value = value;
return;
}
else if (key < current.key)
{
if (current.left == null)
{
current.left = new TreeNode<>(key, value);
return;
}
else
put(current.left, key, value);
}
else
{
if (current.right == null)
{
current.right = new TreeNode<>(key, value);
return;
}
else
put(current.right, key, value);
}
}
}
我最难的是递归。我了解基本递归的工作原理,但使用它来实现平衡的二叉搜索树似乎比最初想象的要困难得多。
【问题讨论】:
标签: java binary-tree binary-search-tree b-tree avl-tree