1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| test = () => { let tree = { key: 1, value: 1, children: [ { key: 2, value: 2, children: [ { key: 4, value: 4, }, { key: 5, value: 5, }, ], }, { key: 3, value: 3, children: [ { key: 6, value: 6, }, { key: 7, value: 7, }, ], }, ], }; console.log(tree, "tree"); const DFS = (tree) => { let list = []; const loop = (tree) => { list.push(tree); if (tree.children && tree.children.length > 0) { for (let i = 0; i < tree.children.length; i++) { loop(tree.children[i]); } } }; loop(tree); return list; }; let array = DFS(tree); console.log(array, "array"); };
|