簡體   English   中英

構建平衡的二叉搜索樹

[英]Building a balanced binary search tree

有沒有一種方法來構建平衡的二叉搜索樹?

例:

1 2 3 4 5 6 7 8 9

       5
      / \
     3   etc
    / \
   2   4
  /
 1

我想有一種方法可以做到這一點,而不使用更復雜的自平衡樹。 否則我可以自己做,但有人可能已經這樣做了:)


謝謝你的回答! 這是最后的python代碼:

def _buildTree(self, keys):
    if not keys:
        return None

    middle = len(keys) // 2

    return Node(
        key=keys[middle],
        left=self._buildTree(keys[:middle]),
        right=self._buildTree(keys[middle + 1:])
        )

對於每個子樹:

  • 找到子樹的中間元素並將其放在樹的頂部。
  • 查找中間元素之前的所有元素,並遞歸使用此算法來獲取左子樹。
  • 找到中間元素之后的所有元素,並遞歸地使用此算法來獲取正確的子樹。

如果您首先對元素進行排序(如示例中所示),則可以在恆定時間內查找子樹的中間元素。

這是用於構造一次性平衡樹的簡單算法。 它不是自平衡樹的算法。

以下是C#中的一些源代碼,您可以自己嘗試:

public class Program
{
    class TreeNode
    {
        public int Value;
        public TreeNode Left;
        public TreeNode Right;
    }

    TreeNode constructBalancedTree(List<int> values, int min, int max)
    {
        if (min == max)
            return null;

        int median = min + (max - min) / 2;
        return new TreeNode
        {
            Value = values[median],
            Left = constructBalancedTree(values, min, median),
            Right = constructBalancedTree(values, median + 1, max)
        };
    }

    TreeNode constructBalancedTree(IEnumerable<int> values)
    {
        return constructBalancedTree(
            values.OrderBy(x => x).ToList(), 0, values.Count());
    }

    void Run()
    {
        TreeNode balancedTree = constructBalancedTree(Enumerable.Range(1, 9));
        // displayTree(balancedTree); // TODO: implement this!
    }

    static void Main(string[] args)
    {
        new Program().Run();
    }
}

本文詳細解釋:

最優時空中的樹重新平衡
http://www.eecs.umich.edu/~qstout/abs/CACM86.html

也在這里:

一次性二進制搜索樹平衡:Day / Stout / Warren(DSW)算法
http://penguin.ewu.edu/~trolfe/DSWpaper/

如果你真的想在飛行中做,你需要一個自平衡樹。

如果你只想構建一個簡單的樹,而不必去平衡它的麻煩,只需將元素隨機化,然后再將它們插入樹中。

將數據的中位數(或更准確地說,數組中最接近的元素與中位數)作為樹的根。 等等遞歸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM