叶到根路径Java

时间:2018-07-29 00:31:41

标签: java arraylist tree

我一直在搜索,但似乎无法理解如何将路径从叶返回到根。

例如:

         A
       /   \
      B     C
     /     / \ 
    D     E   F

因此,如果我做A.find(E),它应该返回[A,C,E];如果我做B.find(D),它应该返回[B,D]

我的尝试:

// Base Case - The root of this Tree is c. Route is just [child]
public List<Person> find(Person c) {
    List<Person> path = new ArrayList<Person>();
    Person p = c;
    while(c != null) {
        path.add(p);
    }
    return path;
}

1 个答案:

答案 0 :(得分:0)

这里是您的问题的解决方案:从任何起始节点搜索到树中指定的 target 节点:

public class PathFind {
    public static void main(String... args) {
        Node dNode = new Node("D", null, null);
        Node bNode = new Node("B", dNode, null);

        Node eNode = new Node("E");
        Node fNode = new Node("F");
        Node cNode = new Node("C", eNode, fNode);

        Node aNode = new Node("A", bNode, cNode);

        System.out.println(aNode.find(null));
        System.out.println(aNode.find(bNode));
        System.out.println(aNode.find(cNode));
        System.out.println(aNode.find(eNode));
        System.out.println(bNode.find(dNode));

        System.out.println(bNode.find(eNode));
        System.out.println(cNode.find(dNode));
    }


    static class Node {
        Node left, right;
        String val;

        public Node(String theVal, Node theLeft, Node theRight) {
            this.val = theVal;
            this.left = theLeft;
            this.right = theRight;
        }

        public Node(String theVal) {
            this(theVal, null, null);
        }

        @Override
        public String toString() {
            return val;
        }

        public List<Node> find(Node theNode) {
            List<Node> path = new ArrayList<>();
            if (find(this, theNode, path)) return path;
            else return null;
        }



        // 

        /**
         * 
         * @param startNode start from the startNode to search;
         * @param theNode the node to search;
         * @param path using a list to record the path along the way;
         * @return to indicate whether there is a path or not;
         */
        private boolean find(Node startNode, Node theNode, List<Node> path) {
            path.add(startNode);
            if (startNode == theNode) return true; 
            if (startNode == null) return false;
            if (find(startNode.left, theNode, path)) return true;
            else path.remove(path.size() - 1); // remove the last for the right search;
            if (find(startNode.right, theNode, path)) return true;
            else path.remove(path.size() - 1);
            return false;
        }
    }

}

涵盖了三种情况以确保其符合要求:

  1. 您可以从树中的任何节点开始到任何节点;
  2. 如果目标节点为null,则将返回预订的第一条路径;
  3. 如果没有这样的路径,则path将是null,表示存在这样的路径;

上面提供的演示的输出:

[A, B, D, null]
[A, B]
[A, C]
[A, C, E]
[B, D]
null
null