大学编程任务:基于访问者模式实现AbstractTree深度计算问询
基于访问者模式计算AbstractTree深度的完整实现方案
嘿,我来帮你搞定这个大学编程任务!先把你给出的树形结构代码补全整理好,然后一步步实现访问者模式来计算树的深度。
第一步:补全并整理现有树形结构代码
你已经定义了核心的树形抽象类和节点/叶子类,我把Node类的代码补全(包括Accept方法和子节点访问方式):
public abstract class AbstractTree { public abstract void Accept(AbstractVisitor abstractVisitor); } public class Leaf : AbstractTree { public override void Accept(AbstractVisitor visitor) { visitor.VisitLeaf(this); } } public class Node : AbstractTree { private AbstractTree Left { get; set; } private AbstractTree Right { get; set; } public Node(AbstractTree left, AbstractTree right) { Left = left; Right = right; } public override void Accept(AbstractVisitor visitor) { visitor.VisitNode(this); } // 提供公共方法让访问者能访问子节点,保证封装性 public AbstractTree GetLeft() => Left; public AbstractTree GetRight() => Right; }
第二步:定义访问者抽象类
根据访问者模式的要求,我们需要定义一个抽象访问者,包含对应不同树形节点的访问方法,以及获取最终计算结果的方法:
public abstract class AbstractVisitor { // 访问叶子节点的抽象方法 public abstract void VisitLeaf(Leaf leaf); // 访问非叶子节点的抽象方法 public abstract void VisitNode(Node node); // 获取计算出的树深度的方法 public abstract int GetDepth(); }
第三步:实现深度计算访问者
接下来编写具体的深度计算访问者,核心逻辑是:
- 叶子节点的深度为1
- 非叶子节点的深度 = 左右子树深度的最大值 + 1
using System; public class DepthCalculatorVisitor : AbstractVisitor { private int _currentDepth; public override void VisitLeaf(Leaf leaf) { // 叶子节点自身深度是1 _currentDepth = 1; } public override void VisitNode(Node node) { // 递归访问左子树,获取左子树深度 node.GetLeft().Accept(this); int leftSubtreeDepth = _currentDepth; // 递归访问右子树,获取右子树深度 node.GetRight().Accept(this); int rightSubtreeDepth = _currentDepth; // 当前节点的深度取左右子树的最大值加1 _currentDepth = Math.Max(leftSubtreeDepth, rightSubtreeDepth) + 1; } public override int GetDepth() { return _currentDepth; } }
第四步:测试代码
我们可以构建一个测试树来验证功能是否正常:
class Program { static void Main(string[] args) { // 构建测试树结构: // 根节点 // / \ // 叶子 节点 // / \ // 叶子 叶子 AbstractTree testTree = new Node( new Leaf(), new Node(new Leaf(), new Leaf()) ); DepthCalculatorVisitor depthVisitor = new DepthCalculatorVisitor(); testTree.Accept(depthVisitor); Console.WriteLine($"这棵树的深度是:{depthVisitor.GetDepth()}"); // 输出结果:3 } }
关键说明
- 访问者模式的优势在于将数据结构和操作分离,计算深度的逻辑完全封装在
DepthCalculatorVisitor中,后续如果需要添加其他树操作(比如计算节点数量、遍历节点),只需要新增访问者类即可,不需要修改树形结构的代码。 - Node类提供
GetLeft()和GetRight()方法是为了保证封装性,避免直接暴露私有属性,同时让访问者能够遍历子树。
内容的提问来源于stack exchange,提问作者user9640512
相关产品推荐
相关产品推荐

