[LeetCode] 559. Maximum Depth of N-ary Tree

多叉树的最大深度。这个题跟104题非常接近,唯一不同的是104题是二叉树,此题是多叉树。这个题可以用两种思路做,分别是BFS和DFS。两种做法的时间和空间复杂度都是O(n)。我就直接上代码了,

[LeetCode] 559. Maximum Depth of N-ary Tree_第1张图片

 

 

Input: root = [1,null,3,2,4,null,5,6]
Output: 3

[LeetCode] 559. Maximum Depth of N-ary Tree_第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

 

BFS

 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 };

 

DFS

 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 };

你可能感兴趣的:([LeetCode] 559. Maximum Depth of N-ary Tree)