計算N叉樹的最大深度,搞點陽間的寫法

其實題目是很簡單的。但這就是函數式編程🐎?👴❤了。

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章