簡體   English   中英

尋找二叉樹中兩個節點之間的路徑

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

我有以下簡單的樹:

在此輸入圖像描述

我的目標是找到兩個管理器節點之間的路徑。

將在cmd中選擇兩個節點輸入。

因此用戶可以鍵入“java BinaryTree manager1 manager2”,輸出將顯示到達第二個管理器所需的路徑。 此示例應輸出以下內容:

'經理1>老板<經理2'

到目前為止我的代碼定義了節點,但我需要一個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;
  }
 }
}`

謝謝你的幫助 :)

在最一般意義上,您必須找到從根到每個節點的路徑,並將它們合並在一起。

如何找到路徑取決於樹的排列; 在最壞的情況下,它需要完全遍歷樹。

在合並步驟中,修剪來自兩個路徑的所有共同祖先,但跟蹤最近的共同祖先。 您想要的路徑與經理1的路徑左側相反,然后是最近的共同祖先(圖中的“Boss”),然后是經理2的路徑。

確保容納一個管理器是另一個管理器的祖先的情況(我描述的合並過程仍然有效,但其中一個修剪路徑將為空)。 還要確保陷阱或適應經理1 ==經理2的情況。

如果您的樹具有超出簡單樹拓撲結構的結構,則可以優化上述某些結構,尤其是路徑查找。

這是打印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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM