class Solution { public: int maxDepth(Node* root) { int depth = 0; if (root != NULL) { queue<Node> Q; Q.push(Node(root->val, root->children)); while (!Q.empty()) { depth++;//层数自增 vector<Node> N; N.clear(); while (!Q.empty()) { Node livenode; livenode = Q.front(); Q.pop(); for (auto n : livenode.children) { N.push_back(Node(n->val, n->children)); } } for (auto n : N) { Q.push(Node(n.val, n.children)); } } } return depth; } };
另一种解法,递归实现:
class Solution { public: int maxDepth(Node* root) { if (root == NULL) return 0; int dep = 0; //当前节点的深度 for (auto n : root->children) { dep = max(dep, maxDepth(n)); //子节点最大深度 } return dep + 1; //子节点最大深度+当前层深度(1) } };
递归的逻辑是:当前节点的最大深度,一定是深度最大的子节点的深度+1。