Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当需要查找二叉树的直径时,泛型树的直径代码不起作用_Java_Recursion_Data Structures_Tree_Binary Tree - Fatal编程技术网

Java 当需要查找二叉树的直径时,泛型树的直径代码不起作用

Java 当需要查找二叉树的直径时,泛型树的直径代码不起作用,java,recursion,data-structures,tree,binary-tree,Java,Recursion,Data Structures,Tree,Binary Tree,几天前,我在学习通用树时,遇到了一个通用树直径的代码,如下所示: 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

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

 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;
  }
今天我在研究二叉树时,遇到了一个类似的问题,即在二叉树中查找直径,但二叉树直径问题的解决方案与此方法不同,是否有办法调整此代码,使其也适用于二叉树?我一直在尝试调整它,使其适用于二叉树,但每次我的代码都会失败一些测试用例。我没有把我的二叉树代码放在这里,因为我写了多种方法,但它们都在一些测试用例中失败。

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

由于查找直径是一个只读操作,因此该算法的工作原理应该基本不变

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

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

Node[]getChildren(){
if(this.left==null){
if(this.right==null)
返回新节点[0];
返回新节点[]{this.right};
}
if(this.right==null)
返回新节点[]{this.left};
返回新节点[]{this.left,this.right};
}
现在将代码中的
node.children
替换为
node.getChildren()
,就完成了

参考文献1: