寻找树的最大深度

时间:2013-03-07 12:18:33

标签: java tree

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

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

4 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:2)

用于查找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类来对数据元素进行hava以及对表示其子节点的节点列表的引用。会是这样的:

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;
    }
}

答案 2 :(得分:0)

    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;
    }

答案 3 :(得分:0)

递归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-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/
  2. https://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/