Java 叶到根路径
我一直在四处寻找,但似乎不明白如何从叶子返回到根的路径 例如:Java 叶到根路径,java,arraylist,tree,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
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;
}
//基本情况-此树的根是c。路线只是[孩子]
公共列表查找(c人){
列表路径=新的ArrayList();
人p=c;
while(c!=null){
路径。添加(p);
}
返回路径;
}
以下是您的问题的解决方案:从任何开始节点搜索到树中指定的目标节点:
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;
}
}
}
如果你想找到根目录,你需要:while(node.parent!=null){node=node.parent}就是这样这个问题有点不清楚:你问
I。。。似乎无法理解如何返回从叶到根的路径。
,但是您说find()
实现应该返回从叶到下叶的路径。我不知道你是在两个方向上寻找元素,还是像例子所示的只有孩子,就像这个例子。find()只是我叫的一个名字,它可以是任何东西。你能告诉我更多关于Person
类的信息吗?除非Person类以某种方式公开Person元素,否则不能仅从Person导航树。相反,必须有另一棵树来容纳人们。那个么,人本身就是树根,还是你们正在穿越另一棵树?不管是哪种方式,您都可以让示例更健壮一些。(推荐阅读:)你的“尝试”显然是假的,因为while(c!=null){path.add(p);}
是一个永无止境的循环(除非c
最初为null),因为c
在循环中没有更新。此外,由于该方法应该“找到”一个后代节点,而您说“Route is just[child]”(我们可以假定它应该命名为children
,即复数),那么代码可能应该以某种方式使用它,您认为呢?请提供更好的“尝试”。
[A, B, D, null]
[A, B]
[A, C]
[A, C, E]
[B, D]
null
null