【问题标题】:Binary search tree - max distance to a LEAF二叉搜索树 - 到 LEAF 的最大距离
【发布时间】:2015-04-18 11:02:21
【问题描述】:

我需要编写一个线性算法来获取 BST,并向每个 NODE 添加一个与 LEAF 的最大距离的字段(如果 NODE 是 LEAF,则距离为零)。

我只需要一个伪代码和运行时间复杂度。

谢谢, 提供。

【问题讨论】:

  • 向我们展示您目前的进展
  • 您是否成功实现了您的功能?如果给出的答案有帮助,通常会对其进行投票或额外标记正确答案。

标签: algorithm sorting data-structures binary-search-tree computer-science


【解决方案1】:

运行时间是树中的项目数。

void addField(node n, int distance)
{
   if(n.left != null)
   {
      addField(n.left, distance + 1);
   }
   if(n.right != null)
   {
      addField(n.right, distance + 1);
   }
   if((n.right == null) && (n.right == null))
   {
      n.distance = distance;
   }
}​

【讨论】:

  • 这将计算到根的距离。 OP想要到一个/任何叶子的(最大)距离。
【解决方案2】:

此函数适用于平衡二叉树,需要对不平衡树等进行一些调整,但您应该能够自己解决。

它在树的根节点上调用,并且会递归地工作

struct Node(){
    int distance;
    Node* leftChild, rightChild;
    bool isLeaf(){ return rightChild==NULL && leftChild==NULL};
}

int dist(Node n){
     if(n.isLeaf()){
          n.distance = 0;
     }else{
          n.distance = 1 + max(dist(n.leftChild),dist(n.rightChild));
     }
     return n.distance;
}

运行时复杂度是线性的,但不是尾递归的。因此,最大节点数受堆栈深度的限制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 2013-01-08
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多