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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>align</title> </head> <body> <button onclick="btnClick()">click</button> </body> <script> function btnClick() { var arr = ['A', 'B', 'C', 'D']; var result = listAlign(arr); window.console.log(result); }
function listAlign(arr) { var trees = []; for (var i = 0; i < arr.length; i++) { var num = arr[i]; var tree = { val: num, parent: null, children: [] }; generateTree(arr, num, tree); trees.push(tree); }
var result = []; for (var i = 0; i < trees.length; i++) { var tree = trees[i]; var arr = []; recurseTree(tree, arr, result); } return result; }
function generateTree(arr, num, tree) { var temp = arr.slice(); for (var i = 0; i < temp.length; i++) { if (temp[i] === num) { temp.splice(i, 1); i--; } } for (var i = 0; i < temp.length; i++) { var item = { val: temp[i], parent: num, children: [] }; tree.children.push(item); generateTree(temp, temp[i], item); } }
function recurseTree(node, arr, result) { var temp = arr.slice(); temp.push(node.val); if (node.children.length === 0) { result.push(temp); } else { var children = node.children; for (var i = 0; i < children.length; i++) { var child = children[i]; recurseTree(child, temp, result); } } } </script> </html>
|