Finding Path Between Two Nodes in a Binary Tree

Conor Bradley picture Conor Bradley · Dec 2, 2014 · Viewed 9.9k times · Source

I have the following simple tree:

enter image description here

My goal is to find the path between the two manager nodes.

The two nodes will be selected input in the cmd.

So the user might type 'java BinaryTree manager1 manager2' and the output will display the path needed to reach the second manager. This example should output the following:

'Manager1 > Boss < Manager2'

The code I have so far defines the nodes however I need a findPath method to print the path.

CODE: `

public class BinaryTree 
    {

 public static void main(String[] args)
 {
  Node boss = new Node(1);
  Node manager1 = new Node(2);
  Node manager2 = new Node(3);

  boss.left = manager1;
  boss.right = manager2;

  String path = findPath(args[0], args[1]);
  System.out.println(path);
  } 

 static class Node
 {
  Node left;
  Node right;
  int value;

  public Node(int value)
  {
   this.value = value;
  }
 }
}`

Thanks for any help :)

Answer

John Bollinger picture John Bollinger · Dec 2, 2014

In the most general sense, you must find the paths from the root to each node, and merge them together.

How you find the paths depends on the arrangement of the tree; in the worst case it requires a full traversal of the tree.

At the merge step, prune all common ancestors from both paths, but keep track of the nearest common ancestor. The path you want is the reverse of what's left of the path to manager 1, then the nearest common ancestor ("Boss" in your diagram), then the path to manager 2.

Make sure to accommodate the cases where one manager is an ancestor of the other (the merge procedure I described still works, but one of the trimmed paths will be empty). Also make sure to trap or accommodate cases where manager 1 == manager 2.

If your tree has structure beyond simple tree topology then it may be possible to optimize some of the above, especially the path-finding.