559. N叉树的最大深度(C++)
题目
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :

我们应该返回其最大深度为3。
说明:
- 树的深度不会超过
1000。 - 树的节点总不会超过
5000。
分析与题解
自底向上
额外自定义一个将深度作为形参的函数遍历到叶节点,从叶节点向上增加,每个node更新深度值,取最大的深度,返回深度+1。代码如下:
+1是加上本身
/*
// 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 getMaxDepth(Node* root, int depth){
if(root==nullptr)
return 0;
//tmp代表到当前结点的深度
int tmp = depth;
for(auto i : root->children){
//因为循环中depth不变,所以取最大值
//采用临时遍历替代
int node_max = getMaxDepth(i, depth+1);
//depth值可能是前一个孩子结点
//每次比较,取孩子中最大的一个
//depth+1已经体现在递归的形参中了
tmp = max(tmp, node_max);
}
return tmp;
}
int maxDepth(Node* root) {
int depth=1;
return getMaxDepth(root, depth);
}
};
自顶向下
不需要额外增加自定义函数:
- 每处理一个节点,深度加一
- 到达叶节点时,深度计算完毕,然后再层层返回。返回较大值
代码如下:
/*
// 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==nullptr)
return 0;
//先求出当前结点的孩子结点的最大值
int depth=0;
for(auto i : root->children){
int count = maxDepth(i);
depth = max(depth, count);
}
return depth+1;
}
};

浙公网安备 33010602011771号