寻找二叉树中两个节点之间的路径

时间:2014-12-02 18:31:19

标签: java data-structures binary-tree nodes args

我有以下简单的树:

enter image description here

我的目标是找到两个管理器节点之间的路径。

将在cmd中选择两个节点输入。

因此用户可以输入' java BinaryTree manager1 manager2'输出将显示到达第二个管理器所需的路径。此示例应输出以下内容:

' Manager1>老板< Manager2'

我到目前为止的代码定义了节点但是我需要一个findPath方法来打印路径。

代码:`

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

感谢您的帮助:)

2 个答案:

答案 0 :(得分:3)

在最一般意义上,您必须找到从根到每个节点的路径,并将它们合并在一起。

如何找到路径取决于树的排列;在最坏的情况下,它需要完全遍历树。

在合并步骤中,修剪两条路径中的所有常见祖先,但跟踪最近的共同祖先。您想要的路径与经理1的路径左侧相反,然后是最近的共同祖先(" Boss"在图中),然后是经理2的路径。

确保容纳一个管理器是另一个管理器的祖先的情况(我描述的合并过程仍然有效,但其中一个修剪路径将为空)。还要确保陷阱或容纳管理员1 ==经理2的情况。

如果您的树具有超出简单树拓扑结构的结构,则可以优化上述某些结构,尤其是路径查找。

答案 1 :(得分:0)

这是打印2个节点之间路径的程序。

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PrintPath {

    static List<Node> path = new ArrayList<Node>();
    static boolean foundBoth;
    /**
     * @param args
     */
    public static void main(String[] args) {
        Node root = Node.createTree();
        printPath(root,9,11);
        System.out.println(path);
    }

    static boolean printPath(Node root,int val1 ,int val2){
        if(root==null){
            return false;
        }
        if(root.data == val1 || root.data == val2){
            addToPath(root);
            if(!foundBoth)
                foundBoth = findDown(root,(root.data==val1)?val2:val1);
            return true;
        }
        if(!foundBoth){
        boolean left = printPath(root.getLeft(), val1, val2);
        if(left){
            addToPath(root);
        }
        boolean right = printPath(root.getRight(), val1, val2);
        if(right)
        addToPath(root);
        return (left|| right);
        }else{
            return true;
        }

    }

    private static void addToPath(Node root) {
        path.add(root);
    }


    static boolean findDown(Node root,int val2){
        if(root == null){
            return false;
        }
        if(root.data == val2){
            addToPath(root);
            return true;
        }
        boolean left = findDown(root.getLeft(), val2);
        if(left){
            addToPath(root);
            return true;
        }
        boolean right = findDown(root.getRight(), val2);
        if(right){
            addToPath(root);
            return true;
        }
        return false;
    }

}
相关问题