2013-03-07 163 views
-1

我知道如何找到二叉树的深度。但我无法推广它为任何树工作。寻找树的最大深度

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

+1

其实我们可以。但你不觉得你应该尝试一些最小的东西吗? – Maroun 2013-03-07 12:20:08

回答

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

Java实现找到k元树的深度:

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