java树结构遍历_树形结构,java_树遍历统计总数,树形结构,java - phpStudy
时间: 2023-11-27 22:52:37 浏览: 75
数据结构 树的遍历
首先需要定义一个树结构的节点类,包含节点值和子节点列表:
```java
class TreeNode {
int val;
List<TreeNode> children;
public TreeNode(int val) {
this.val = val;
children = new ArrayList<>();
}
}
```
然后可以实现树的遍历方法,比如先序遍历:
```java
public void preOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
for (TreeNode child : root.children) {
preOrder(child);
}
}
```
统计树中节点总数可以使用递归方式,每个节点的子节点数目即为它的贡献,加上1就是以它为根的子树的总节点数:
```java
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int count = 1;
for (TreeNode child : root.children) {
count += countNodes(child);
}
return count;
}
```
最后可以通过一个示例来测试:
```java
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
root.children.add(node2);
root.children.add(node3);
root.children.add(node4);
node2.children.add(node5);
node2.children.add(node6);
node4.children.add(node7);
System.out.print("Pre-order traversal: ");
preOrder(root);
System.out.println();
System.out.println("Total number of nodes: " + countNodes(root));
}
```
输出结果:
```
Pre-order traversal: 1 2 5 6 3 4 7
Total number of nodes: 7
```
阅读全文