function search(arr, key, start, end){ if(start > end){ return -1; } var end = end === undefined ? arr.length - 1 : end; var start = start || 0; var mid = parseInt((start+end)/2); if(key == arr[mid]){ return mid; }else if(key < arr[mid]){ return search(arr, key, start, mid - 1) }else{ return search(arr, key, mid+1, end) } }View Code
function search(arr, key){ var start = 0, end = arr.length - 1; while(start <= end){ var mid = parseInt((start+end)/2); if(key == arr[mid]){ return mid }else if(key < arr[mid]){ end = mid - 1 }else{ start = mid + 1 } }; return -1; }View Code
function preorderTraversal(root){ let res = []; test(root, res); return res; } function test(node, res){ if(!node) return; res.push(node.val); test(node.left, res); test(node.right, res); }View Code
function preorderTraversal(root){ const list = []; const stack = []; if(root) stack.push(root) while(stack.length > 0) { const curNode = stack.pop() // 第一步的时候,先访问的是根节点 list.push(curNode.val) // 我们先打印左子树,然后右子树 // 所以先加入栈的是右子树,然后左子树 if(curNode.right !== null) { stack.push(curNode.right) } if(curNode.left !== null) { stack.push(curNode.left) } } return list }View Code
function inorderTraversal(root){ let res = []; test(root, res); return res; } function test(node, res){ if(!node) return; test(node.left, res); res.push(node.val); test(node.right, res); }View Code
function inorderTraversal(root){ let res = []; test(root, res); return res; } function test(node, res){ if(!node) return; test(node.left, res); test(node.right, res); res.push(node.val); }View Code
function test(nums){ let all = nums.reduce((a,b) => a+b); let res = -1; let sd = 0; for(let i = 0; i < nums.length;i++){ let jk = all - sd - nums[i] if(sd == jk){ res = i; break } sd+=nums[i] } return res; }View Code