1,多维数组扁平化。原数组[[0],[2,3,4],1,[1,[2,3]]],输出[0,2,3,4,1,1,2,3]
{ //判断当前数组是否有子数组 function hasChildArray(arr) { return arr.some(element => { if (Array.isArray(element)) { has = true; return true; } }); } let sourceArr = [[0], [2, 3, 4], 1, [1, [2, 3]]]; let result = [];
//递归 (function doFunc(arr) { if (hasChildArray(arr)) { for (let i = 0, l = arr.length; i < l; i++) { if (typeof arr[i] == "number") { result.push(arr[i]); } else if (Array.isArray(arr[i])) { doFunc(arr[i]); } } } else { result=result.concat(arr); } })(sourceArr); console.log(result); }
2,二叉树tree ,根节点是root,判断是否存在一条完整路径,其路径上节点的值之和为target,输出布尔值。
举例:下面的树,是否存在target=7的一条完整路径(从根节点到叶节点),该路径上各个节点之和=target?
6
/
2 3
/ /
-1 3 0
这版本1:该版本创建二叉树的方法比较“笨”
{
//定义节点的数据结构
class Node {
constructor(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
}
//定义二叉树
class BTree {
constructor() {
this.list = [];
}
addRoot(node) {
if (node != null) {
this.list.push(node);
}
}
addLeft(pNode, node) {
this.list.push(node);
pNode.left = node;
}
addRight(pNode, node) {
this.list.push(node);
pNode.right = node;
}
//根据数组中的索引返回node
getNode(index) {
return this.list[index];
}
getNodeList() {
return this.list;
}
}
const lable = "MK";
//创建示例中的二叉树
let bTree = new BTree();
//第一层 根节点
bTree.addRoot(new Node(6, null, null));
//第二层
bTree.addLeft(bTree.getNode(0), new Node(2, null, null));
bTree.addRight(bTree.getNode(0), new Node(3, null, null));
//第三层
bTree.addLeft(bTree.getNode(1), new Node(-1, null, null));
bTree.addRight(bTree.getNode(1), new Node(3, null, null));
bTree.addLeft(bTree.getNode(2), new Node(0, null, null));
function hasPathSum(node, target) {
console.log(node.value);
//根节点
if (!node.left && !node.right) {
return node.value == target;
}
//左右子节点
return (
(node.left && hasPathSum(node.left, target - node.value)) ||
(node.right && hasPathSum(node.right, target - node.value))
);
}
console.time(lable);
console.log(hasPathSum(bTree.getNode(0), 11));
console.timeEnd(lable);
}
版本2:精简版
{
//定义二叉树
class BTree {
constructor(middle, left, right) {
if (middle!=undefined) {
this.value=middle;
if (left!=undefined) this.left = left;
if (right!=undefined) this.right = right;
}
}
}
/**
* 创建一个树
* arr:一个代表二叉树的多维数组
*/
function makeBTree(arr) {
if (arr) {
if (arr.length == 1) return new BTree(arr[0], null, null);
return new BTree(arr[0], makeBTree(arr[1]), makeBTree(arr[2]));
}
}
const lable = "MK";
//创建示例中的二叉树
let bTree = makeBTree([6, [2, [-1], [3]], [3, [0]]]);
// let bTree = makeBTree([6, [2],[-1]]);
function hasPathSum(node, target) {
console.log(node);
//根节点
if (node.left==undefined && node.right==undefined) {
return node.value == target;
}
//左子节点
return (
(node.left!=undefined && hasPathSum(node.left, target - node.value)) ||
(node.right!=undefined && hasPathSum(node.right, target - node.value))
);
}
console.time(lable);
console.log(hasPathSum(bTree, 11));
console.timeEnd(lable);
}