当前位置: 首页 > 面试题库 >

建立平衡的二叉搜索树

阙庆
2023-03-14
问题内容

有没有建立平衡的二叉搜索树的方法?

例:

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();
    }
}


 类似资料: