当前位置: 代码迷 >> 综合 >> 使用TS对树进行深度和广度遍历
  详细解决方案

使用TS对树进行深度和广度遍历

热度:22   发布时间:2023-10-10 20:28:36.0
tree = {Id: 1,Name: "成品",Childs: [{Id: 2,Name: "半成品1",Childs: [{Id: 5,Name: "半成品1-1",Childs: [{ Id: 8, Name: "半成品1-1-1", Childs: [] }]},{ Id: 6, Name: "半成品1-2", Childs: [] }]},{ Id: 3, Name: "半成品2", Childs: [] },{ Id: 4, Name: "半成品3", Childs: [] }]};1.深度遍历使用递归private trace(node, f) {if (node) {f(node);}node.Childs.forEach(element => {this.trace(element, f);});}2.广度遍历private Ntrace(node) {let nodes = new Array();nodes.push(node);while (nodes.length > 0) {let Child = nodes.shift();console.log(Child.Name);Child.Childs.forEach(element => {nodes.push(element);});}}输出mounted() {console.log("广度优先");this.Ntrace(this.tree);console.log("深度优先");this.trace(this.tree, f => {console.log(f.Name);});}

 

  相关解决方案