打印两个节点之间的路径

时间:2014-12-03 01:42:17

标签: java path binary-tree

我有以下树形结构:

enter image description here

在java中实现:

public class myprogram
{
    public static void main(String[] args)
    {

        Node Boss= new Node(0, "Boss");
        Node Manager1= new Node(1, "Manager1");
        Node Manager2= new Node(1, "Manager2");
        Node AssistantManager = new Node(2,"AssistantManager");
        Node Employee3 = new Node(3,"Employee3");
        Node Employee4 = new Node(3,"Employee4");
        Node Employee1 = new Node(6, "Employee1");
        Node Employee2 = new Node(6, "Employee2");

        Boss.left = Manager1;
        Boss.right = Manager2;

        Manager1.left = AssistantManager;
        Manager1.right = null;

        AssistantManager.left = Employee1;
        AssistantManager.right = Employee2;


        Manager2.left = Employee3;
        Manager2.right = Employee4;
    }

    static class Node
    {
        Node left;
        Node right;
        int value;
        String name;
        public Node(int value, String name)
        {
           this.value = value;
           this.name = name;
        }
    }
}

我的目标是创建一个方法,找到此树结构中两个节点之间的路径。例如,输入可能是:

String path = findPath(Boss,"AssistantManager",  "Manager2");
System.out.println(path);

鉴于此,找到路径'方法应该返回' AssistantManager> Manager1>老板< Manager2'

如果输入是' Employee1,Employee2',则应该给出:

Employee1 > AssistantManager < Employee2

我一直试图实现这一点,所以任何有关如何编码的帮助都将非常感激。

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是将treeRoot的路径转换为arg1(AssistantManager),将root路径转换为arg2(&#34; Manager2&#34;) 然后找到共同的祖先。 例如助理经理的路径:老板 - 经理1 - 助理经理 Manager2的路径:老板 - 经理2 所以路径:AssistantManager - Manager1 - boss - Manager2

和第二个例子 老板 - 经理1 - 助理经理 - E1 老板 - 经理1 - 助理经理 - E2 = E1 - 助理经理 - e2。

这是一些伪代码

List<String> firstPath = findSinglePath(Node tree, String first) (E1, AssManager, manager1m Boss)
List<String> secondPath = findSinglePath(Node tree, String second) (E2, AssManager, manager1m Boss)
path += "";
for each firstPath
add to path += currentNode + >
if (secondPath contains currentNode) break loop (common ancestor)

for each secondPath
if (firstPath contains currentNode) break loop
else path += < + currentNode