Zna*_*kus 10 c# python binary-tree
有没有一种方法来构建平衡的二叉搜索树?
例:
1 2 3 4 5 6 7 8 9
5
/ \
3 etc
/ \
2 4
/
1
Run Code Online (Sandbox Code Playgroud)
我想有一种方法可以做到这一点,而不使用更复杂的自平衡树.否则我可以自己做,但有人可能已经这样做了:)
谢谢你的回答!这是最后的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:])
)
Run Code Online (Sandbox Code Playgroud)
对于每个子树:
如果您首先对元素进行排序(如示例中所示),则可以在恒定时间内查找子树的中间元素.
这是用于构造一次性平衡树的简单算法.它不是自平衡树的算法.
以下是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();
}
}
Run Code Online (Sandbox Code Playgroud)
本文详细解释:
最佳时空中树的重新平衡
http://www.eecs.umich.edu/~qstout/abs/CACM86.html
也在这里:
一次性二进制搜索树平衡:Day/Stout/Warren(DSW)算法
http://penguin.ewu.edu/~trolfe/DSWpaper/
如果你真的想在飞行中做,你需要一个自平衡树.
如果你只想构建一个简单的树,而不必去平衡它的麻烦,只需将元素随机化,然后再将它们插入树中.
| 归档时间: |
|
| 查看次数: |
9970 次 |
| 最近记录: |