题目:
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
示例 1:
输入:root = [1,null,3,2,4,null,5,6]
输出:3
示例 2:
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:5
提示:
- 树的深度不会超过 1000 。
- 树的节点数目位于 [0, 104] 之间。
思路:
依然可以提供递归法和迭代法,来解决这个问题,思路是和二叉树思路一样的。
代码:
- 递归法
/*
// 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 == NULL) return 0;
int depth = 0;
for(int i = 0; i < root->children.size(); i++){
// 若第i个节点有子节点,得到depth1会比取max才能保证取到最大深度,因为有
// 若第i个节点有子节点,得到depth2
// depth1 > depth2,但depth2会把depth1覆盖,所以要取max
depth = max(depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};
- 迭代法
在这里插入代码片class Solution {
public:
int maxDepth(Node* root) {
queue<Node*> que1;
if(root != NULL) que1.push(root);
int depth = 0;
while(!que1.empty()){
int size = que1.size();
while(size--){
Node* node = que1.front();
que1.pop();
for(int i = 0; i < node->children.size(); i++){
que1.push(node->children[i]);
}
}
depth++;
}
return depth;
}
};
总结:
N叉树和普通二叉树的区别是左右节点统一由children表示,其他都一样。