算法小结
1 二叉树
定义树节点形式
interface TreeNode {
val: string
right: Object | null
left: Object | null
}
1.1 层序遍历
语义解析:层序遍历指的是二叉树根据层级进行遍历。
利用队列的思想,将左右节点插入到队列中,然后出队。
队列
var levelOrder = function(root) {
if (!root) {
return [];
}
const quene = new Array();
quene.push(root);
const arr = [];
while(quene.length) {
const popNode = quene.shift();
arr.push(popNode.val);
popNode.left && quene.push(popNode.left);
popNode.right && quene.push(popNode.right);
}
return arr;
};
1.2 前序遍历
解析:先访问根,然后访问左子树,最后访问右子树
递归实现
function preOrder(node) {
if (!node) {
return;
}
console.log(node.val)
preOrder(node.left);
preOrder(node.right);
}
栈实现
function preOrder(node) {
if (!node) {
return;
}
let stack = [node];
while(stack.length) {
const top = stack.pop();
console.log(top.val);
top.right && stack.push(top.right);
top.left && stack.push(top.left);
}
}
1.3 中序遍历
解析:先访问左子树,然后访问根,最后访问右子树
递归实现
function preOrder(node) {
if (!node) {
return;
}
preOrder(node.left);
console.log(node.val);
preOrder(node.right);
}
1.4 后序遍历
解析:先后访问左子树,然后访问右子树,最后访问根
递归实现
function preOrder(node) {
if (!node) {
return;
}
preOrder(node.left);
preOrder(node.right);
console.log(node.val);
}
2 排序
2.1 堆排序
javascript建堆算法
function createHeep(arr) {
const length = arr.length;
for(let i = Math.floor(length / 2); i >= 0; i--) {
adjustHeep(arr, i, length);
}
}
function adjustHeep(arr, r, l) {
let nR = r * 2 + 1;
while(r < l) {
if (nR + 1 < l && arr[nR] > arr[nR + 1]) {
nR += 1;
}
if (arr[nR] < arr[r] && nR < l) {
[arr[r], arr[nR]] = [arr[nR], arr[r]];
r = nR;
nR = r * 2 + 1;
}
else {
break;
}
}
}
剑指 Offer 40. 最小的k个数
function getLeastNumbers(arr, k) {
const length = arr.length;
if (length === 0) {
return [];
}
if (k === length) {
return arr;
}
createHeep(arr);
let newArr = [];
for(let i = 1; i <= k; i++) {
newArr.push(arr[0]);
[arr[0], arr[length - i]] = [arr[length - i], arr[0]];
adjustHeep(arr, 0, length - i);
}
return newArr;
};
2.1 快速排序
function quick (list, left, right) {
let index = 0;
if (list.length > 1){
index = partition(list, left, right);
left < index - 1 && quick(list, left, index - 1);
index < right && quick(list, index, right);
}
}
function partition(list, left, right){
let mid = list[Math.floor((right + left) / 2)];
while (left <= right) {
while (list[left] < mid) {
left++;
}
while (list[right] > mid) {
right--;
}
if (left <= right) {
[list[left], list[right]] = [list[right], list[left]];
left++;
right--;
}
}
return left;
}