Guest User

Recursive tree walk

a guest
Mar 30th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. import java.util.ArrayList;
  2.  
  3. public class Main {
  4.  
  5.     public static void main(String[] args) {
  6.         Main main = new Main();
  7.         main.start();
  8.     }
  9.  
  10.     static class Node {
  11.  
  12.         public Node(String name) {
  13.             this.name = name;
  14.         }
  15.  
  16.         String name;
  17.         ArrayList<Node> children = new ArrayList<>();
  18.  
  19.     }
  20.  
  21.  
  22.     void start() {
  23.         // Create an example tree of nodes:
  24.         Node root = new Node("Root");
  25.  
  26.         Node root_child1 = new Node("Root child 1");
  27.         root.children.add(root_child1);
  28.         Node root_child2 = new Node("Root child 2");
  29.         root.children.add(root_child2);
  30.  
  31.  
  32.         Node parent = new Node("Parent");
  33.         root.children.add(parent);
  34.  
  35.         Node parent_child1 = new Node("Parent child1");
  36.         parent.children.add(parent_child1);
  37.  
  38.         Node parent_child2 = new Node("Parent child2");
  39.         parent.children.add(parent_child2);
  40.  
  41.  
  42.         // Print the tree:
  43.         this.printNode(root);
  44.     }
  45.  
  46.  
  47.     void printNode(Node node) {
  48.         System.out.println(node.name);
  49.         for (Node child_node : node.children) {
  50.             printNode(child_node);
  51.         }
  52.     }
  53. }
  54.  
  55.  
  56. Output:
  57. Root
  58. Root child 1
  59. Root child 2
  60. Parent
  61. Parent child1
  62. Parent child2
Advertisement
Add Comment
Please, Sign In to add comment