559. N叉树的最大深度
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :
解题思路: 本题既可以用DFS做,也可以用BFS做。
- DFS
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
int maxDepth(Node* root) {
if (!root) return 0;
int res = 0;
for (auto t : root->children) {
res = max(res, maxDepth(t));
}
return res + 1;
}
};
- BFS
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
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) {
Node* t = q.front(); q.pop();
for (auto nd : t->children) {
if (nd) q.push(nd);
}
}
++res;
}
return res;
}
};