Java语言怎么使用链表存储二叉树的连接矩阵的连接图呢?这个连接图的定义在Java里的实现是什么
2条回答 默认 最新
关注效果如图

代码及分析
import java.util.LinkedList; // 二叉树节点类 class BinaryTreeNode { int value; BinaryTreeNode left; BinaryTreeNode right; public BinaryTreeNode(int value) { this.value = value; } } // 连接矩阵类 class ConnectionMatrix { LinkedList<BinaryTreeNode> connections; public ConnectionMatrix() { connections = new LinkedList<>(); } public void addConnection(BinaryTreeNode node) { connections.add(node); } } public class Main { public static void main(String[] args) { // 构建示例二叉树 BinaryTreeNode root = new BinaryTreeNode(1); BinaryTreeNode node2 = new BinaryTreeNode(2); BinaryTreeNode node3 = new BinaryTreeNode(3); BinaryTreeNode node4 = new BinaryTreeNode(4); BinaryTreeNode node5 = new BinaryTreeNode(5); root.left = node2; root.right = node3; node2.left = node4; node2.right = node5; // 创建连接矩阵 ConnectionMatrix matrix = new ConnectionMatrix(); // 添加节点连接关系到连接矩阵 matrix.addConnection(root); matrix.addConnection(node2); matrix.addConnection(node3); matrix.addConnection(node4); matrix.addConnection(node5); // 打印连接矩阵中的节点值 for (BinaryTreeNode node : matrix.connections) { System.out.println(node.value); } } }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 1无用