【问题标题】:Turning a regular Binary Search Tree into an Balanced Binary Search Tree将常规二叉搜索树变成平衡二叉搜索树
【发布时间】: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


    【解决方案1】:

    你只想要一个二叉搜索树,对吗?如果是这样,则实际上不需要密钥(用于 M-ary 树)。

    这并不完全是一个答案,但希望这将至少有助于简化您的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多