Question:
You are given one binary tree, find the path from one node to another.
public static LinkedList<Integer> printPath(Node root, Node n1, Node n2) {
Node temp = root;
LinkedList<Integer> rootToN1 = new LinkedList<Integer>();
LinkedList<Integer> rootToN2 = new LinkedList<Integer>();
pathFromRootToNode(temp, n1, new ArrayList<Integer>(), rootToN1);
pathFromRootToNode(root, n2, new ArrayList<Integer>(), rootToN2);
int prev = 0;;
while (true) {
if (rootToN1.size() > 0 && rootToN2.size() > 0 && rootToN1.get(0) == rootToN2.get(0)) {
prev = rootToN1.get(0);
rootToN1.remove();
rootToN2.remove();
} else {
rootToN2.add(0, prev);
for (Integer i : rootToN1) {
rootToN2.add(0, i);
}
break;
}
}
return rootToN2;
}
// the path from root the a specific node
public static void pathFromRootToNode(Node root, Node n, ArrayList<Integer> stack, LinkedList<Integer> list) {
if (root == null) return;
stack.add(root.value);
if (root == n) {
list.addAll(stack);
}
if (root.leftChild != null) {
pathFromRootToNode(root.leftChild, n, stack, list);
}
if (root.rightChild != null) {
pathFromRootToNode(root.rightChild, n, stack, list);
}
// after searching the left part, we need to remove the added value
stack.remove(stack.size() - 1);
}
class Node {
Node leftChild = null;
Node rightChild = null;
int value;
Node(int value) {
this.value = value;
}
}
本文介绍了一种在二叉树中寻找从根节点到指定节点路径的方法,并提供了一个具体的实现示例。通过递归遍历的方式,可以找到任意两个节点的路径。
1万+

被折叠的 条评论
为什么被折叠?



