给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
示例 1:
输入:root = [1,null,3,2,4,null,5,6]
输出:3
解:上个题一毛一样
1、迭代“
class Solution {
public:
int maxDepth(Node* root) {
if(!root) return 0;
queue<Node *> treeQueue;
treeQueue.push(root);
int depth = 0;
while (!treeQueue.empty()) {
int nSize = treeQueue.size();
for (int i = 0; i < nSize; i++) {
Node * tempNode = treeQueue.front();
treeQueue.pop();
for (int j = 0; j < tempNode -> children.size(); j++) {
if (tempNode -> children[j]) treeQueue.push(tempNode -> children[j]);
}
}
depth++;
}
return depth;
}
};
2、递归
class Solution {
public:
int maxDepth(Node* root) {
if(!root) return 0;
int depth = 0;
for (int i = 0; i < root -> children.size(); i++) {
depth = max(depth, maxDepth(root -> children[i]));
}
return depth + 1;
}
};