559. N叉树的最大深度

给定一个 N 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

Solution1(递归版):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
int maxDepth(Node* root) {
return dfs(root,1);
}

int dfs(Node* node, int m){
if(!node) return 0;
int max = m;
for(int i = 0; i < node->children.size(); i++){
max = std::max(dfs(node->children[i], m+1), max);
}
return max;
}
};

递归版本。

我的写法为:

定义空节点的深度为0,这样在做最大值比较的时候返回的是其父节点的深度。

这样做可以在root为空的时候不用做特殊处理。直接会返回0。

评论区有人是这样写的:

1
2
3
4
5
6
7
8
9
public int maxDepth(Node root) {    //DFS递归写法
if(root == null)
return 0;
int depth = 0;
for(int i = 0;i<root.children.size();i++){
depth = Math.max(depth,maxDepth(root.children.get(i)));
}
return depth+1;
}

由下至上来确定最大深度,但是需要额外判断根节点为空的情况。

Solution2(迭代版):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public:
int maxDepth(Node* root) {
if(!root) return 0;
int maxDep = 0;
queue<Node*> q;
q.push(root);
//队列中始终保持存储的节点都为同一层。
while(!q.empty()){
int n = q.size();
//当前层有结点。
maxDep++;
//将当前层所有元素pop掉。
for(int i = 0; i < n ;i++){
Node* t = q.front(); q.pop();
//将子节点push进队列。
for(int j = 0; j < t->children.size(); j++){
q.push(t->children[j]);
}
}
}
return maxDep;
}
};

迭代版利用层次遍历。

每到一层,深度加1。然后将该层的所有结点pop掉。继续将下一层的结点push进来。