简体   繁体   English

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

[英]Finding Path Between Two Nodes in a Binary Tree

I have the following simple tree: 我有以下简单的树:

在此输入图像描述

My goal is to find the path between the two manager nodes. 我的目标是找到两个管理器节点之间的路径。

The two nodes will be selected input in the cmd. 将在cmd中选择两个节点输入。

So the user might type 'java BinaryTree manager1 manager2' and the output will display the path needed to reach the second manager. 因此用户可以键入“java BinaryTree manager1 manager2”,输出将显示到达第二个管理器所需的路径。 This example should output the following: 此示例应输出以下内容:

'Manager1 > Boss < Manager2' '经理1>老板<经理2'

The code I have so far defines the nodes however I need a findPath method to print the path. 到目前为止我的代码定义了节点,但我需要一个findPath方法来打印路径。

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 :) 谢谢你的帮助 :)

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. 您想要的路径与经理1的路径左侧相反,然后是最近的共同祖先(图中的“Boss”),然后是经理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. 还要确保陷阱或适应经理1 ==经理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. 如果您的树具有超出简单树拓扑结构的结构,则可以优化上述某些结构,尤其是路径查找。

Here is the program to print the path between 2 nodes. 这是打印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;
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在二叉树中找到两个节点之间的距离 - Find distance between two nodes in binary tree 寻找两个节点之间的最短路径 - Finding shortest path between two nodes 在负权重的加权DAG中找到两个节点之间的最短路径 - Finding shortest path between two nodes in a weighted DAG with negative weights 贪婪递归算法,用于为具有节点和边权重的完全二叉树中的所有节点寻找最短路径 - greedy and recursive algorithm for finding shortest path for all nodes in a complete binary tree with node and edge weights 找到二叉树的两个叶子之间的最大路径和(Java) - Find the maximum path sum between two leaves of a binary tree (Java) 递归查找二叉树中节点的路径 - Recursively finding the path to a node in a Binary Tree 二叉树中两个节点的第一个共同祖先 - first common ancestor of two nodes in a binary tree 算法 - O(n)中二进制搜索树的每两个节点之间的距离之和? - Algorithm- Sum of distances between every two nodes of a Binary Search Tree in O(n)? 如何找到树中两个节点之间的路径? - How to find the path between 2 nodes in a tree? 在二叉搜索树中查找每个深度的节点数量 - Finding the amount of nodes for each depth in a Binary Search Tree
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM