找到所有树节点的叶子节点

demo

比如上面的树有三个叶子节点,second节点有两个叶子节点,third节点有一个叶子节点,root节点有三个叶子节点

const tree = {
  text: "root",
  children: [
    { text: "001", children: [{ text: "003" }, { text: "004" }] },
    {
      text: "002",
      children: [
        { text: "005", children: [{ text: "007" }] },
        { text: "006" },
        { text: "008" }
      ]
    }
  ]
};

function setLeafCount(tree) {
  if (
    Reflect.has(tree, "children") &&
    Array.isArray(tree["children"]) &&
    tree.children.length > 0
  ) {
    tree.leafCount = tree.children.reduce((pre, cur) => {
      return pre + setLeafCount(cur);
    }, 0);

    return tree.leafCount;
  } else {
    //叶子节点
    return 1;
  }
}

const count = setLeafCount(tree);
console.info(count);//count 是根节点下所有叶子节点的个数

console.info(JSON.stringify(tree));

最后得到的结果

结果

叶子节点不需要leafCount,非叶子节点需要用leafCount表明他下面有多少个叶子节点,这样从构造出的树就能方便的看到非叶子节点下面的叶子节点的个数

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容