简体   繁体   English

你如何以 O(log n) 倍的复杂度计算平衡二叉搜索树的高度?

[英]How do you calculate the height of balanced Binary Search Tree in O(log n) times complexity?

I understand that in order to compute the height of a Binary Search Tree in O(n) we can use the following function我知道为了在 O(n) 中计算二叉搜索树的高度,我们可以使用以下函数

public static int treeHeight(Node root) {
      if (root == null) {
         return -1;
      }

      int left = treeHeight(root.left) + 1;
      int right = treeHeight(root.right) + 1;

      return Math.max(left, right);
   }  

However, given the fact that the tree is [balanced][2] how can we calculate the height of Binary Search Tree in O(log n).然而,鉴于树是[平衡的][2],我们如何在 O(log n) 中计算二叉搜索树的高度。

The given problem:给定的问题:

It's not possible.这是不可能的。

If the bottom row were filled out in a predictable fashion it could be done.如果底行以可预测的方式填写,则可以完成。 For example, if the last row were always filled out left-to-right you could descend down the left side in O(log n) time since the left side would be guaranteed to have max height.例如,如果最后一行总是从左到右填写,您可以在 O(log n) 时间内从左侧下降,因为左侧将保证具有最大高度。

In the problem statement the nodes in the bottom row can be anywhere.在问题陈述中,底行中的节点可以在任何地方。 The exact height can't be computed in O(log n) time.无法在 O(log n) 时间内计算出确切的高度。 You can get within 1 of the height in O(log n) steps, but to get the exact height you may have to examine up to n/2 nodes at the bottom of the tree to find the stragglers (if any).您可以在 O(log n) 步中获得高度的 1 以内,但要获得确切的高度,您可能需要检查树底部最多 n/2 个节点以找到落后者(如果有)。

The worst case is if the last level is completely full and every single node in the last level has to be checked for children.最坏的情况是,如果最后一层完全满了,并且必须检查最后一层中的每个节点是否有子节点。 There would be n/2 nodes and two checks per node, thus n checks in total.将有 n/2 个节点和每个节点两个检查,因此总共有 n 个检查。 There wouldn't be any children in this case, but it'd still take O(n) checks to verify it.在这种情况下不会有任何孩子,但仍然需要 O(n) 检查来验证它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM