Question: use java to write Find the Shortest Path from one given tree node to another given tree node For the last problem, you will find

use java to write

Find the Shortest Path from one given tree node to another given tree node

For the last problem, you will find two elements, and return an iterator that can traverse the elements along the shortest possible path (following the connections that exist in the tree between parent and child nodes) to get from one given tree node to another given tree node. You can use both the path to root and lowest common ancestor in your solution.

This method will be added to the LinkedBinaryTree.java file, and has the following header:

public Iterator shortestPath(T targetOne, T targetTwo) throws ElementNotFoundException{

we already have to method:

public Iterator pathToRoot(T targetElement) throws ElementNotFoundException{

ArrayUnorderedList pathToRoot = new ArrayUnorderedList();

pathToRootAgain(targetElement, root, pathToRoot);(there is a mistake, how to change?)

if (pathToRoot.isEmpty() == true){

throw new ElementNotFoundException("Binary Tree");

}

return pathToRoot.iterator();

}

public void PathToRootAgain(T targetElement,T root, int n, ArrayUnorderedList pathToRoot)

{

if (root == null) {

return ;

}

if (root.data == n) {(.data has a mistake how to change?)

return ;

}

if (root.left != null) PathToRootAgain(root.left, n, pathToRoot);(.left can not be resloved, how to change?)

if (root.right != null) PathToRootAgain(root.right, n, pathToRoot) ;

pathToRoot.add(root);(how to create method add(T)?)

return ;

}

public T lowestCommonAncestor( T targetOne, T targetTwo) throws ElementNotFoundException{

Iterator one = pathToRoot(targetOne);

Iterator two = pathToRoot(targetTwo);

ArrayUnorderedList onPathOne = new ArrayUnorderedList();

while(one.hasNext()){

onPathOne.addToRear(one.next());

}

while(two.hasNext()){

T temp = two.next();

if(onPathOne.contains(temp)){

return temp;

}}

return root.element;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!