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;
}
}