Java 一般树转换为二叉树后,如何使用二叉树查找给定一般树节点“v”的父级?

Java 一般树转换为二叉树后,如何使用二叉树查找给定一般树节点“v”的父级?,java,algorithm,tree,binary-tree,Java,Algorithm,Tree,Binary Tree,我尝试了两种实现,但都不太管用 这是我完全坚持的一个实现 /** Returns the parent of a given node or the node itself if it is the root */ public Position<E> parent(Position<E> v) throws IllegalArgumentException { if(bTree.isRoot(v)) { return v; } // returns the

我尝试了两种实现,但都不太管用

这是我完全坚持的一个实现

/** Returns the parent of a given node or the node itself if it is the root */
public Position<E> parent(Position<E> v) throws IllegalArgumentException {
      if(bTree.isRoot(v)) { return v; } // returns the node v itself if v is the root.
      Position<E> parent = bTree.root(); 
      // execute this recursive method and return the parent. 
      return preorderTraversal(parent, v, null);
  }

/* This is the helper method that will traverse the binary tree in PreOrder. It updates 
 * the parent until the node v has been found.
 */
private Position<E> preorderTraversal(Position<E> focusNode, Position<E> v, Position<E> parent) {

     System.out.print(focusNode.getElement() + "\t");

      if (focusNode != null && v != focusNode && hasLeft(focusNode)) {
          parent = focusNode;
          System.out.print("setting parent to: " + parent.getElement() + "\t");
          preorderTraversal(bTree.left(focusNode), v, parent);
      }
      else if (focusNode != null && v != focusNode && hasRight(focusNode)){
          preorderTraversal(bTree.right(focusNode), v, parent);
      }
      return parent;
  }

// -------------- EXTRA HELPER METHODS ---------------
private boolean hasLeft(Position<E> temp ) {
      if (bTree.left(temp) != null) return true;
      else return false;
  }

  private boolean hasRight(Position<E> temp ) {
      if (bTree.right(temp) != null) return true;
      else return false;
  }

这里的问题似乎是它遍历左子树,并更新正确的父节点,但在返回值时,它总是返回根节点。我似乎不明白为什么会这样。另一个原因是,当遍历正确的子树时,我的父节点总是错误的。请帮忙

你对待左右都不一样,却没有给人动力。您尚未指定一般树是什么?一个猜测是每个节点可以有两个以上的子节点,但是,由于转换的节点似乎具有可比性:原始节点有多少个值?它是如何转换成二叉树的左侧引用是后代引用,右侧是兄弟引用?给出一个URL可能是合适的。 组合检查:如果null==focusNode | | v==focusNode return parent;。 在左侧循环之前,不要将值赋给与其有意义的名称相矛盾的变量,而应传递适当的值:preorderTraversalbTree.leftfocusNode,v,focusNode;。 如果你在条件语句的不同部分进行了不同的处理,而没有无可争议和明显的原因,那么就写一条评论:当你在右边重复时,为什么要经过父对象? 引用方法注释的一个例子。考虑将它们升级到