How can tree structures be represented in Java?

In Java, it is possible to achieve tree structure output using recursion.

Firstly, it is necessary to create a class that represents a tree node, which includes a data field and a list or array pointing to child nodes. Let’s assume the class for the tree node is named TreeNode, containing an integer data field and a list type child node list.

Next, you can traverse and output the tree structure using recursion. The specific steps are as follows:

  1. Create a method to recursively traverse tree nodes and output the data field of each node.
  2. A method is defined, which takes a TreeNode, a prefix, and a boolean variable as parameters. It prints out the TreeNode’s data along with its relationship to the parent node. It then iterates through the children of the current node, printing them out accordingly. If there are children, it recursively calls the method on each child node.
  3. Create a tree in the main program, pass the root node and an empty string as parameters, and call the above method for output.
  4. The main method creates a tree structure with nodes and their children, then prints the tree starting from the root node.

Running the program will display the output result in a tree structure.

└── 1
    ├── 2
    │   ├── 4
    │   └── 5
    └── 3

This achieves the output of a tree structure.

bannerAds