比如上面的树有三个叶子节点,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表明他下面有多少个叶子节点,这样从构造出的树就能方便的看到非叶子节点下面的叶子节点的个数
网友评论