# [LeetCode] Maximum Depth of N-ary Tree N叉树的最大深度

Given a n-ary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

For example, given a 3-ary tree:

We should return its max depth, which is 3.

Note:

1. The depth of the tree is at most 1000.
2. The total number of nodes is at most 5000.

class Solution {
public:
int maxDepth(Node* root) {
int res = 0;
helper(root, 1, res);
return res;
}
void helper(Node* node, int cur, int& res) {
if (!node) return;
if (node->children.empty()) res = max(res, cur);
for (Node* child : node->children) {
helper(child, cur + 1, res);
}
}
};

class Solution {
public:
int maxDepth(Node* root) {
if (!root) return 0;
int res = 1;
for (Node* child : root->children) {
res = max(res, maxDepth(child) + 1);
}
return res;
}
};

class Solution {
public:
int maxDepth(Node* root) {
if (!root) return 0;
int res = 0;
queue<Node*> q{{root}};
while (!q.empty()) {
for (int i = q.size(); i > 0; --i) {
auto t = q.front(); q.pop();
for (auto child : t->children) {
if (child) q.push(child);
}
}
++res;
}
return res;
}
}; 

Maximum Depth of Binary Tree

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/148544/Java-Top-down-DFS-solutions

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/167010/DFS-and-BFS-solutions-in-C%2B%2B.

https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/151804/Solution-Python-C%2B%2B-Simple-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中...)

 微信打赏 Venmo 打赏
posted @ 2018-10-29 21:41  Grandyang  阅读(2988)  评论(0编辑  收藏  举报