// 1.深度优先遍历的递归写法
function deepTraversal(node) {
let nodes = [];
if (node != null) {
nodes.push[node];
let children = node.children;
for (let i = 0; i < children.length; i++) {
deepTraversal(children[i]);
}
}
return nodes;
}
// 2.深度优先遍历的非递归写法
function deepTraversal(node) {
let nodes = [];
if (node != null) {
let stack = [];
// 同来存放将来要访问的节点
stack.push(node);
while (stack.length !== 0) {
let item = stack.pop();
// 正在访问的节点
nodes.push(item);
let children = item.children;
for (let i = children.length - 1; i >= 0; i--) {
// 将现在访问点的节点的子节点存入stack,供将来访问
stack.push(children[i]);
}
}
}
return nodes;
}
// 3.广度优先遍历的递归写法
function wideTraversal(node) {
let nodes = [], i = 0;
if (node != null) {
nodes.push(node);
wideTraversal(node.nextElementSibling);
node = nodes[i++];
wideTraversal(node.firstElementChild);
}
return nodes;
}
// 4.广度优先遍历的非递归写法
function wideTraversal(node) {
let nodes = [], i = 0;
while (node != null) {
nodes.push(node);
node = nodes[i++];
let children = node.children;
for (let i = 0; i < children.length; i++) {
nodes.push(children[i]);
}
}
return nodes;
}
对于算法来说 无非就是时间换空间 空间换时间
示例1:
nums1 = [1, 3] nums2 = [2]
中位数是 2.0
示例2:
nums1 = [1, 2] nums2 = [3, 4]
中位数是 (2 + 3) / 2 = 2.5
const findMedianSortedArrays = function(nums1, nums2) {
const lenN1 = nums1.length;
const lenN2 = nums2.length;
const median = Math.ceil((lenN1 + lenN2 + 1) / 2);
const isOddLen = (lenN1 + lenN2) % 2 === 0;
const result = new Array(median);
let i = 0; // pointer for nums1
let j = 0; // pointer for nums2
for (let k = 0; k < median; k++) {
if (i < lenN1 && j < lenN2) {
if (nums1[i] < nums2[j]) {
result[i + j] = nums1[i++];
} else {
result[i + j] = nums2[j++];
}
} else if (i < lenN1) {
result[i + j] = nums1[i++];
} else if (j < lenN2) {
result[i + j] = nums2[j++];
}
}
if (isOddLen) {
return (result[median - 1] + result[median - 2]) / 2;
} else {
return result[median - 1];
}
};
实现原理: