You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Visual Studio的TreeView中用C#统计节点数量与树的深度

统计TreeView节点总数与树深度的C#实现

嘿,这需求我之前做WinForms项目的时候经常碰到,给你整理了两种靠谱的实现方式——递归(简单直观)和迭代(避免大量节点时栈溢出),你可以根据自己的场景选:

一、统计所有节点总数

TreeView的节点是嵌套结构,所以得遍历所有层级的节点。这里给你两种写法:

1. 递归实现(代码简洁,适合节点数不多的场景)

private int CountAllNodes(TreeNodeCollection nodes)
{
    int count = nodes.Count;
    foreach (TreeNode node in nodes)
    {
        // 递归统计子节点数量,加到总数里
        count += CountAllNodes(node.Nodes);
    }
    return count;
}

// 调用方式:
int totalNodes = CountAllNodes(treeView1.Nodes);
MessageBox.Show($"总节点数:{totalNodes}");

2. 迭代实现(更稳定,适合节点数量大的场景)

用队列遍历所有节点,避免递归深度过大导致的栈溢出问题:

private int CountAllNodesIterative(TreeNodeCollection nodes)
{
    int count = 0;
    Queue<TreeNode> nodeQueue = new Queue<TreeNode>();

    // 先把根节点都加入队列
    foreach (TreeNode node in nodes)
    {
        nodeQueue.Enqueue(node);
        count++;
    }

    while (nodeQueue.Count > 0)
    {
        TreeNode currentNode = nodeQueue.Dequeue();
        // 遍历当前节点的所有子节点,加入队列并计数
        foreach (TreeNode childNode in currentNode.Nodes)
        {
            nodeQueue.Enqueue(childNode);
            count++;
        }
    }
    return count;
}

// 调用方式和递归版一样:
int totalNodes = CountAllNodesIterative(treeView1.Nodes);

注意:如果需要排除隐藏节点,可以在计数前加判断 if (node.Visible) 再累加。

二、计算树的深度

树的深度指的是从根节点到最远叶子节点的最长路径的节点数(比如根节点单独存在时深度为1)。同样给你两种实现:

1. 递归实现

private int GetTreeDepth(TreeNodeCollection nodes)
{
    int maxDepth = 0;
    foreach (TreeNode node in nodes)
    {
        // 子节点的深度 = 当前节点层级 + 子树的深度
        int childDepth = 1 + GetTreeDepth(node.Nodes);
        if (childDepth > maxDepth)
        {
            maxDepth = childDepth;
        }
    }
    // 如果没有节点,返回0;否则返回最大深度
    return nodes.Count == 0 ? 0 : maxDepth;
}

// 调用方式:
int treeDepth = GetTreeDepth(treeView1.Nodes);
MessageBox.Show($"树的深度:{treeDepth}");

2. 迭代实现

用队列记录每个节点的当前层级,遍历过程中跟踪最大层级:

private int GetTreeDepthIterative(TreeNodeCollection nodes)
{
    if (nodes.Count == 0) return 0;

    int maxDepth = 0;
    Queue<Tuple<TreeNode, int>> nodeQueue = new Queue<Tuple<TreeNode, int>>();

    // 根节点的层级是1
    foreach (TreeNode node in nodes)
    {
        nodeQueue.Enqueue(Tuple.Create(node, 1));
    }

    while (nodeQueue.Count > 0)
    {
        var current = nodeQueue.Dequeue();
        TreeNode currentNode = current.Item1;
        int currentDepth = current.Item2;

        // 更新最大深度
        if (currentDepth > maxDepth)
        {
            maxDepth = currentDepth;
        }

        // 子节点的层级是当前层级+1,加入队列
        foreach (TreeNode childNode in currentNode.Nodes)
        {
            nodeQueue.Enqueue(Tuple.Create(childNode, currentDepth + 1));
        }
    }
    return maxDepth;
}

如果你的需求里把根节点算成深度0,只需要把初始层级改成0,返回的时候逻辑对应调整就行。

内容的提问来源于stack exchange,提问作者Stelios Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:25:05