algorithm - 在 O(1) 中构建二叉树?

标签 algorithm time-complexity binary-tree

我的 friend 在面试中被问到这个问题:

Generate a finite but arbitrarily large binary tree in O(1). The method generate() should return a binary tree whose size is unbounded but finite.

面试后我们都考虑了很长时间,但我们最多只能想出O(n) 的解决方案。

我们如何在 O(1) 中生成?有可能吗?还有更多的东西吗?

最佳答案

这是非常不明确的,但可以大胆猜测他们想要什么:

def generate():
    if coinflip():
        return Node()
    return Node(left=None, right=generate())

O(1) 预期运行时间,无限制的返回树大小(以及无限制的可能运行时间,包括以 0 概率永远运行)。我们每次以 50% 的概率随机决定是否继续使树更深。

关于algorithm - 在 O(1) 中构建二叉树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49502112/

相关文章:

java - 在java中获取二叉搜索树的根

python - 修改python中的二叉树

algorithm - 判断两棵二叉树是否相等

arrays - 混淆 "Find a pair with the given difference"中的时间复杂度

c - C 中的循环挑战 : can it be done another way?

c# - 计算一周内工作的天数而不循环?

python - 修改范围之间的一组值

algorithm - 戈朗 : benchmark Radix Tree Lookup

algorithm - 什么是 splay 树中的摊销复杂性?

java - 计算这个具体算法的时间复杂度