求一个多叉树的深度,例如
class MdNode {
String name;
List<MdNode> children; //儿子节点列表
}
已知一个node,计算他的深度,有兴趣的可以自己动手写写看。
思路基本上是:
没有子节点,则深度为1(自身);
有子节点,则深度为子节点中最大深度子节点的深度+1(自身);
递归,我的具体实现如下:
class MdNode {
String name;
List<MdNode> children; //儿子节点列表
int getMaxDepth() {
if (!hasChild()) {
return 1;
}
int y = 1;
children.forEach((child) {
if (child.getMaxDepth() > y) y = child.getMaxDepth();
});
return y + 1;
}
///是否有子节点
bool hasChild() {
return children != null && children.length > 0;
}
}