【问题标题】:Code for diameter of generic tree not working when required to find out diameter of binary tree当需要找出二叉树的直径时,通用树的直径代码不起作用
【发布时间】:2021-03-25 20:00:30
【问题描述】:

几天前,我在学习泛型树,遇到了一个泛型树直径的代码,如下所示:

 static int diameter = Integer.MIN_VALUE;
  public static int findDia(Node node){
      int dch = -1; // dch = deepest child height
      int sdch =-1; // sdch = second deepest child height
      
      for(Node child : node.children){ // children of current node are in an arraylist , every node has data + reference of arraylist of its children
          int ch = findDia(child); // ch = child height
          if(ch>dch){
              sdch=dch;
              dch=ch;
          }else if(ch>sdch){
              sdch=ch;
          }
      }
      if(sdch+dch+2>diameter){
          diameter = sdch+dch+2;
      }
      return dch+1;
  }

今天在研究二叉树时,遇到了一个类似的问题,即在二叉树中查找直径,但是针对二叉树直径问题给出的解决方案与此方法不同,有没有办法调整此代码它也适用于二叉树吗?我一直在尝试对其进行调整,使其适用于二叉树,但每次我的代码都失败了一些测试用例。我没有把我的二叉树代码放在这里,因为我已经编写了多种方法,但是它们都失败了一些测试用例。

【问题讨论】:

    标签: java recursion data-structures tree binary-tree


    【解决方案1】:

    二叉树是通用树的特殊版本[1],因此任何适用于通用树的只读算法树也适用于二叉树。

    由于查找直径是一个只读操作,因此算法的工作原理应该几乎没有变化。

    唯一的区别是通用树有一个子列表,而二叉树只有 2 个独立的子引用,但这是代码应该很容易适应的一个小细节。

    你可以例如使用一种方法增强二叉树Node 类,使其看起来像一个通用树节点:

    Node[] getChildren() {
        if (this.left == null) {
            if (this.right == null)
                return new Node[0];
            return new Node[] { this.right };
        }
        if (this.right == null)
            return new Node[] { this.left };
        return new Node[] { this.left, this.right };
    }
    

    现在将代码中的node.children 替换为node.getChildren(),就完成了。

    参考 1: Difference between General tree and Binary tree

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多