上一篇是根据某一个数字画出当前数字所在的分支。本篇将介绍输入一个层级,输出该层级的所有分支。
实现思路
因为一个数字它只能从奇数或者偶数过来,是逆推过程。比如8只能从偶数过来是16,因为(8-1)/3不是自然数,所以不能从奇数过来。
仍然使用echart做展示
export interface EchartTree {
name: number;
children: EchartTree[];
}
将最后一层的节点存到数组里,方便计算下一层
type tailListTotal = EchartTree[][]
实现生成树形结构的方法,传入当前最后一层的节点数组,并为最后一层节点的children添加下一层节点,同时把下一层节点存到数组中
type getSequence = (tailList: EchartTree[]) => void
具体实现
export interface EchartTree {
name: number;
children: EchartTree[];
}
export default class Service {
// 初始化数据
constructor(deep?: number) {
this.deep = deep || 10
this.getSequence([this.root])
}
// 要计算的深度
protected deep: number;
// 初始节点设置到8,因为1和4会不断循环
protected root: EchartTree = {
name: 8,
children: [],
};
// 每一层的所有节点
protected tailListTotal: EchartTree[][] = []
getRoot(): EchartTree {
return this.root;
}
getTailList(): EchartTree[][] {
return this.tailListTotal;
}
// 根据某一层节点,生成下一层
protected getSequence(tailList: EchartTree[]): void {
const tmpList: EchartTree[] = [];
for (const v of tailList) {
const tmp: EchartTree = {
name: v.name * 2,
children: [],
};
tmpList.push(tmp);
v.children.push(tmp);
const oddNum = (v.name - 1) / 3;
if (oddNum % 2 === 1) {
const tmp2: EchartTree = {
name: oddNum,
children: [],
};
tmpList.push(tmp2);
v.children.push(tmp2);
}
}
this.tailListTotal.push(tmpList);
this.deep--;
if (this.deep > 0) {
this.getSequence(tmpList);
}
}
}