其實題目是很簡單的。但這就是函數式編程🐎?👴❤了。
var maxDepth = function (root) {
function traverse(root, depth) {
return Math.max(
depth,
...root.children.map((child) => traverse(child, depth + 1))
);
}
return root ? traverse(root, 1) : 0;
};
順帶一提,我今天才知道,Math.max
在沒有參數時會返回-Infinity
。
同理,Math.min
在沒有參數時會返回Infinity
。