繁体   English   中英

求一棵树的最大深度

[英]Finding maximum depth of a tree

我知道如何找到二叉树的深度。 但我不能将它概括为适用于任何树。

有人可以概述一个用于查找树(不一定是二叉树)深度的伪代码。

int findDepthOfTree(tree):
    int deepest = 0;
    for (child of root node)
       deepest = max(deepest, findDepthOfTree(child))
    return deepest + 1

查找 k-ary 树深度的 Java 实现:

static int findDepth(Node root) {
    int deepest = 0;
    if (root.children != null) {
        for (Node child : root.children) {
            deepest = Math.max(deepest, findDepth(child));
        }
    }
    return deepest+1;
}

这假设实现了以下 Node 类以包含数据元素以及对代表其子节点的节点列表的引用。 会是这样的:

class Node {
    int data;
    List<Node> children;

    public Node (int data, List<Node> children) {
        this.data = data;
        this.children = children;
    }
    public Node (int data) {
        this.data = data;
        this.children = null;
    }
}
    public static int GetMaxDepth(MyTree node)
    {
        List<int> result = new List<int>();
        foreach (var childNode in node.Items)
        {
            result.Add(GetMaxDepth(childNode));
        }
        return (result.Any() ? result.Max(n => n) : 0) + 1;
    }

递归 StreamAPI 解决方案: O(n)

    int calculateMaxDepth(Node node) {
        if (node == null)
            return 0;

        var localDepth = node.children
           .stream()
           .map(NodeService::calculateMaxDepth)
           .max(Comparator.naturalOrder())
           .orElse(0); // if root has no children -> return 0
        return ++localDepth;
    }

迭代队列解决方案: O(n)

    int calculateMaxDepth(Node rootNode) {
        if (rootNode == null) return 0;

        int height = 0;

        // level representing queue
        Queue<Node> nodesQueue = new LinkedList<>();
        nodesQueue.add(rootNode);

        while (true) {
            // amount of nodes on level
            int nodesCount = nodesQueue.size();
            if (nodesCount == 0) return height;

            ++height;

            // deque all nodes of current level and
            // enqueue all nodes of next level
            while (nodesCount > 0) {
                var currentLevelNode = nodesQueue.remove();
                var validChildrenNodes = currentLevelNode.children
                    .parallelStream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
                nodesQueue.addAll(validChildrenNodes);
                --nodesCount;
            }
        }
    }

有关更多信息,您可以访问:

  1. https://www.geeksforgeeks.org/write-ac-program-to-find-the-maximum-depth-or-height-of-a-tree/
  2. https://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM