Java tree storage structure implementation example code
1、 Tree
Different from linear structures such as linear table, stack and queue, tree is a nonlinear structure.
A tree has only one root node. If a tree has multiple root nodes, it is no longer a tree, but a collection of multiple trees, also known as forest.
2、 Parent node representation of tree
Except for the root node, each node in the tree has a parent node. In order to record the parent-child relationship between nodes in the tree, you can add a parent field for each node to record the parent node of the node.
Test class:
Program output:
Treeparent $node [data = root, parent = - 1] depth of this tree: 2 first child node of root node: treeparent $node [data = node 1, parent = 0] depth of this tree: 3
3、 Child node chain representation
Let the parent node remember all its children.
Test class:
Program output:
Treechild $node [data = root, first = - 1] the root node after adding child nodes: treechild $node [data = root, first = 1] the depth of this tree: 2 the first child node of the root node: treechild $node [data = node 1, first = - 1] the first child node of this tree: treechild $node [data = node 1, first = 4] the depth of this tree: 3
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.