LeetCode 559 Maximum Depth of N-ary Tree

题意

给定一颗 N 叉树 的根节点,返回树的深度.

例 :

1
2
3
4
5
6
7
给予树:
1
/ | \
3 2 4
/ \
5 6
返回深度 3.

解法

采用 DFS (深度优先算法),代码比较简单,不再赘言。

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
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;

public Node() {}

public Node(int _val,List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public int maxDepth(Node root) {
int depth = 1;
if (root == null)
return 0;
for (Node n : root.children){
depth = Math.max(depth, maxDepth(n) + 1);
}
return depth;
}
}

Runtime: 1 ms, faster than 99.56% of Java online submissions for Maximum Depth of N-ary Tree.
Memory Usage: 49.8 MB, less than 5.41% of Java online submissions for Maximum Depth of N-ary Tree.

  • 本文作者: 赵俊
  • 本文链接: http://www.zhaojun.im/leetcode-559/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!