首页 > 解决方案 > 从根节点到java中的点的某些点没有得到正确的路径

问题描述

我试图通过使用递归算法找出从根节点到给定点的路径。对于某些点,我得到了正确的路径,但对于某些点,我得到了不正确的路径。请查看以下链接以获取有关该问题的详细说明。

问题陈述

我已经为此输入输出尝试了以下代码。

public static List<String> findPathToNode(Node rootNode, Point toFind) {
    // @ToDo Implement this routine
    List<String> nodeList = new ArrayList<>();
    if(toFind.getX() < rootNode.getWidth() && toFind.getY() <rootNode.getWidth()){
      return getPath(rootNode, toFind, nodeList);
    }
   return nodeList;
  }

  //Recursive function to loop through all nodes of tree and return empty LinkedList
  // if point not found or NOT Empty with the path to the point, if point is found
  private static List <String> getPath(Node root, Point p, List<String> result) {
    if(p.getX() >-1 && p.getY() >-1) {
      if (root != null) {
        result.add(root.getId());
        List<Node> childNodes = root.getChildren();
        if (childNodes != null && !childNodes.isEmpty()) {
          Node child = null;
          for (Node node : childNodes) {

             (isLeftBoundCondtionMet(node,p) && isTopBoundCondtionMet(node,p)) {
              child = node;
            }
          }
          getPath(child, p, result);
        }
      }
    }
    return result;
  }

  public static Boolean isLeftBoundCondtionMet(Node root, Point p) {
    return root.getLeft() <= p.getX() && (p.getX() < (root.getLeft() + root.getWidth()));
  }

  public static Boolean isTopBoundCondtionMet(Node root, Point p) {
    return root.getTop() <= p.getY() && (p.getY() < (root.getTop() + root.getHeight()));
  }

它给了我以下错误

org.junit.ComparisonFailure: Error in output. Unexpected path for point: java.awt.Point[x=32,y=3] 
Expected :node/node-1/node-1-6/node-1-6-8/node-1-6-8-4
Actual   :node/node-1/node-1-6

标签: javarecursiondata-structuresbinary-search-tree

解决方案


推荐阅读