简体   繁体   English

二叉树广度优先搜索算法

[英]Binary tree breadth first search algorithm

In a binary tree BFS algorithm, can someone please help me understand why we do a height - 1 in the code below.在二叉树 BFS 算法中,有人可以帮助我理解为什么我们在下面的代码中做一个height - 1 I wrote this code but it never worked until I figured out online you need to do a height - 1.我写了这段代码,但直到我在网上发现你需要做一个高度 - 1 之前它才起作用。

public class BreadthFirstSearch {

public static int calculateHeightOfTree(Node root) {
    if (root == null) {
        return 0;
    } else {
        return 1 + Math.max(calculateHeightOfTree(root.leftNode), calculateHeightOfTree(root.rightNode));
    }
}

public static void printDataAtAllLevels(Node root, int height) {
    for (int i = 1; i <= height; i++) {
        printDataAtGivenLevel(root, i);
    }
}

public static void printDataAtGivenLevel(Node root, int height) {
    if (root == null) {
        return;
    }
    if (height == 1) {
        System.out.println(root.data);
    } else {
        printDataAtGivenLevel(root.leftNode, height - 1);
        printDataAtGivenLevel(root.rightNode, height - 1);
    }
}

public static void main(String[] args) {
    Node node = new Node(1);
    node.leftNode = new Node(2);
    node.rightNode = new Node(3);
    node.leftNode.leftNode = new Node(4);
    node.leftNode.rightNode = new Node(5);

    System.out.println("Level order traversal of binary tree is ");
    int height = calculateHeightOfTree(node);
    System.out.println("HEIGHT: " + height);
    printDataAtAllLevels(node, height);
}

Well, if you want to print the data of level n of the tree, that's equivalent to printing the data of level n-1 of the left and right sub-trees.那么,如果要打印树的n级数据,就相当于打印了左右子树的n-1级数据。 Therefore, when you pass the left and right sub-trees to the recursive calls, you should request to print the data of level reduced by 1.因此,当您将左右子树传递给递归调用时,您应该请求打印级别减少 1 的数据。

For example, since the root of the tree has level 1, the left and right children of the root have level 2. So if you wish to print all the data of level 2 for the original tree, that's equivalent to printing the data of level 1 for the left and right sub-trees.例如,由于树的根为 1 级,因此根的左右子节点为 2 级,所以如果要打印原始树的所有 2 级数据,就相当于打印了该级的数据1 为左右子树。

If you would not decrease height it would always be the same value in every (recursive) method call.如果您不减少height则在每个(递归)方法调用中它始终是相同的值。

Therefore the recursion would not stop because height == 1 would always be false.因此递归不会停止,因为height == 1总是假的。 It would only stop because root == null would be true, because you reached the end of a sub-tree.它只会因为root == null为真而停止,因为您到达了子树的末尾。 But in this case there would be no output, but only a return .但在这种情况下,将没有输出,而只有return

Because the height int printDataAtGivenLevel(Node root, int height) is the height relative to the root.因为高度 int printDataAtGivenLevel(Node root, int height)是相对于根的高度。 So if you want to print level 2 from the root , you need to print level 1 from root.left and root.right .所以如果你想从root打印 level 2,你需要从root.leftroot.right打印 level 1。

这样您就可以打印从高度最低的节点开始到高度最大的节点的高度。

Honestly, when I read Binary tree breadth first search algorithm , I do not think about a series of depth-limited DFS traversals, but visiting nodes of a given level, and collecting the ones for the next level, rinse and repeat:老实说,当我阅读二叉树广度优先搜索算法时,我并没有考虑一系列深度限制的DFS遍历,而是访问给定级别的节点,并收集下一级的节点,冲洗并重复:

static void doStuff(Node root){
  List<Node> current=new ArrayList<>();
  current.add(root);
  int level=0;
  int total=0;
  while(current.size()>0){
    level++;
    System.out.println("Level "+level+":");
    List<Node> next=new ArrayList<>();
    for(int i=0;i<current.size();i++){
      Node node=current.get(i);
      System.out.print(node.data+" ");
      if(node.leftNode!=null)
        next.add(node.leftNode);
      if(node.rightNode!=null)
        next.add(node.rightNode);
      total++;
    }
    System.out.println();
    current=next;
  }
  System.out.println(total+" nodes visited, from "+level+" levels");
}

Then it can be tricked into one list:然后它可以被欺骗到一个列表中:

static void doStuff(Node root){
  List<Node> nodes=new LinkedList<>();
  nodes.add(root);
  int level=0;
  int total=0;
  int current;
  while((current=nodes.size())>0){
    level++;
    System.out.println("Level "+level+":");
    while(current-->0){
      Node node=nodes.removeFirst();
      System.out.print(node.data+" ");
      if(node.leftNode!=null)
        nodes.add(node.leftNode);
      if(node.rightNode!=null)
        nodes.add(node.rightNode);
      total++;
    }
    System.out.println();
  }
  System.out.println(total+" nodes visited, from "+level+" levels");
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM