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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| var arr = [3, 9, 20, null, null, 15, 7]
function toBeLink1(arr, x, obj) { obj = obj || {} x = x || 0 obj.value = arr[x] var lIndex = 2 * x + 1 var rIndex = 2 * x + 2 if (arr[lIndex] === 0 || arr[lIndex]) { toBeLink(arr, lIndex, obj.left = {}) } if (arr[rIndex] === 0 || arr[rIndex]) { toBeLink(arr, rIndex, obj.right = {}) } return obj }
class TreeNode { constructor(value) { this.value = value } insert(values) { if (!values.length) return this const queue = [this] let i = 0 while (queue.length > 0) { const current = queue.shift() for (let side of ['left', 'right']) { if (!current[side]) { if (values[i] !== null) { current[side] = new TreeNode(values[i]) } i++ if (i >= values.length) return this } if (current[side]) queue.push(current[side]) } } return this } }
function toBeLink(arr) { if (arr.length === 0) return {} const myTree = new TreeNode(arr[0]) myTree.insert(arr.slice(1)) return myTree }
function toBeLink(arr, obj = {}, queue = []) { if (!arr || arr[0] === null || arr[0] === '' || arr[0] === undefined) return obj obj.value = arr[0] queue.push(obj)
let i = 1 while(i <= arr.length) { const current = queue.shift() for (let side of ['left', 'right']) { const arri = arr[i] i++ console.log(i, arr.length) if (i > arr.length) return obj if (arri === null) continue
current[side] = { value: arri } if (arri !== undefined) { queue.push(current[side]) } } } }
function toBeLink(arr) { if (arr.length === 0 || arr[0] === null) return {} var obj = { value: arr[0] } var queue = [obj] var i = 1 var sideArr = ['left', 'right'] while (i <= arr.length) { var current = queue.shift() for (var j = 0; j < sideArr.length; j++) { var arri = arr[i] var side = sideArr[j] i++ if (i > arr.length) return obj if (arri === null) continue
current[side] = { value: arri } queue.push(current[side]) } } }
var root = { value: 3, left: { value: 9, }, right: { value: 20, left: { value: 15, }, right: { value: 7, } } }
|