Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example 1:
Input: root = [1,null,3,2,4,null,5,6] Output: 3Example 2:
Input: 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] Output: 5
Constraints:
- The depth of the n-ary tree is less than or equal to
1000
. - The total number of nodes is between
[0, 10^4]
.
多叉树的最大深度。这个题跟104题非常接近,唯一不同的是104题是二叉树,此题是多叉树。这个题可以用两种思路做,分别是BFS和DFS。两种做法的时间和空间复杂度都是O(n)。
BFS
JavaScript实现
1 /** 2 * @param {Node} root 3 * @return {number} 4 */ 5 var maxDepth = function (root) { 6 if (root === null) return 0; 7 let depth = 0; 8 let queue = [root]; 9 while (queue.length) { 10 let size = queue.length; 11 for (let i = 0; i < size; i++) { 12 let cur = queue.shift(); 13 queue.push(...cur.children); 14 } 15 depth++; 16 } 17 return depth; 18 };
Java实现
1 class Solution { 2 public int maxDepth(Node root) { 3 if (root == null) { 4 return 0; 5 } 6 int depth = 0; 7 Queue<Node> queue = new LinkedList<>(); 8 queue.offer(root); 9 while (!queue.isEmpty()) { 10 int size = queue.size(); 11 for (int i = 0; i < size; i++) { 12 Node cur = queue.poll(); 13 for (Node child : cur.children) { 14 queue.offer(child); 15 } 16 } 17 depth++; 18 } 19 return depth; 20 } 21 }
DFS
JavaScript实现
1 /** 2 * @param {Node} root 3 * @return {number} 4 */ 5 var maxDepth = function (root) { 6 if (root === null) return 0; 7 let res = 0; 8 for (let child of root.children) { 9 res = Math.max(res, maxDepth(child)); 10 } 11 return res + 1; 12 };
Java实现
1 class Solution { 2 public int maxDepth(Node root) { 3 if (root == null) { 4 return 0; 5 } 6 int res = 0; 7 for (Node child : root.children) { 8 res = Math.max(res, maxDepth(child)); 9 } 10 return res + 1; 11 } 12 }