【问题标题】:Java Binary Search Tree _ the distance from root to nearest leafJava二叉搜索树_从根到最近叶子的距离
【发布时间】:2015-09-21 02:02:30
【问题描述】:

我想知道计算离根最近的叶子距离的基本算法 在二叉搜索树中

我想用这样的代码,

public int closeness() {
    return closeness(root);
}

public int closeness(Node x) {

} 

谢谢。

【问题讨论】:

  • 你的树平衡了吗?
  • 不需要平衡

标签: java binary-search-tree


【解决方案1】:

你需要取每个分支的“接近度”的最小值加一:

public int closeness(Node x) {
  if (x == null) {
    return Integer.MAX_VALUE;
  }
  if (x.left == null && x.right == null) {
    return 0;
  }
  return Math.min(closeness(x.left), closeness(x.right)) + 1;
}

或者,如果没有忽略 Math.min() 中的空分支的“MAX_VALUE”技巧,会稍微冗长一些

public int closeness(Node x) {
  if (x.left == null) {
    if (x.right == null) {
      return 0;
    }
    return closedness(x.right) + 1;
  }
  if (x.right == null) {
    return closedness(x.left) + 1;
  }
  return Math.min(closeness(x.left), closeness(x.right)) + 1;
}

【讨论】:

  • 有什么问题?也许澄清/扩展问题?
  • emmm 好的叶节点没有任何子节点,但是当它没有一个子节点时 if 语句返回。但是,当我将其更改为 && 时,它会导致空指针异常错误...
  • 啊,抱歉,错误地将 null 视为叶节点,现在应该修复。
  • 哦,谢谢你一直帮助我:) 你能解释一下“return Integer.MAX_VALUE;”这部分吗?
  • 这只是为了避免分别检查 x.left 和 x.right 是否为空,确保在计算子封闭性时通过 Math.min() 忽略空分支
【解决方案2】:

实现您的要求的一个快速想法是递归遍历您的 BST(左子树和右子树),并在此过程中计算到达叶节点之前必须通过的节点数。最后,您可以使用一个简单的 MIN/MAX 函数来确定离根最近的叶节点。请注意,该想法适用于计算距离,而不是实际(最近)叶节点本身。我认为,实现这一点应该不会太困难。如果您有任何其他问题,请随时提出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2013-02-11
    相关资源
    最近更新 更多