【问题标题】:How to traverse this binary tree in O(log n) time?如何在 O(log n) 时间内遍历这棵二叉树?
【发布时间】:2019-02-16 00:52:27
【问题描述】:

今天面试,问题是:

给定这棵二叉树,编写一个函数以在 O(log n) 时间内到达任何给定索引。

注意:此二叉树中的数字是索引而不是值。考虑值是空的。

该函数接受 2 个参数:根和我们想要的索引。

def reach_To_Index(root, index)

这棵树和他给我的一模一样

           1
        /     \
      2        3
     / \      /  \
   4    5    6    7
 /  \                
8    9

我的回答是:如果它是二叉搜索树,我可以这样做,但他的回答是,it is not a Binary Search Tree,但你可以使用模数得出答案!

我的问题是可能吗?如果是的话,请任何人写这个函数!!

【问题讨论】:

  • 为什么一定是二叉搜索树?二叉搜索树搜索值。你只是在做索引。请注意,这些数据的存储方式相当于堆,由于这种规则结构,它通常是存储在数组中的树。注意 6 = 2 * 3,3 是 6 的父节点,6 是 3 的左子节点。还要注意 5 = 2 * 2 + 1 和 2 是 5 的父节点,5 是右子节点。你能找到关联一级节点及其父节点的模式吗?现在将其扩展到任意级别。
  • 如果它是一个完整二叉树(你没有说它是否是),这很容易,因为你可以计算级别和位置,从而进行遍历。见stackoverflow.com/q/12359660/1256452
  • 如果您修改图表以将索引写入二进制(如11011100 等),Alexander Reynolds 描述的模式应该更多很明显。
  • 9 的父级是 4 (9 = 2 * [4] + 1)。 4 的父级是 2 (4 = 2 * [2] + 0)。 2 的父级是 1。所以要到达 9,你向左移动到 2,向左移动到 4,向右移动到 9。对于二进制,1001(又名 9)的父级是 100,而 1001 在右边。 100s 的父母是 10,而 100 在左边。 10 的父母是 1,10 在左边。
  • @Vic 他们希望我实现的主要想法是编写一个递归函数来显示如何访问索引。在每个级别,您都必须决定向左还是向右。那就是他们想让我做的。一旦达到该索引,您就可以返回索引、数据或执行其他操作。但主要是如何到达那里,每个级别的条件是什么?

标签: python python-3.x python-2.7


【解决方案1】:
def reach_to_index(node, index):
    if index == 1:
        return node

    power = 2**(int(math.floor(math.log(index, 2))) - 1)
    new_index = power + index % power

    if index < 3 * power:
        return reach_to_index(node.left, new_index)
    return reach_to_index(node.right, new_index)

使用索引的二进制表示:

def reach_to_index(node, index):
    for bit in bin(index)[3:]:
        node = node.left if bit == '0' else node.right
    return node

【讨论】:

  • 谢谢。这是一个很好的解决方案!
猜你喜欢
  • 2023-03-20
  • 2022-11-02
  • 2016-07-27
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多