介绍
在平常LootCode做题时,链表和树的题输入都是建立好的,而我们做笔试的时候通常需要自己建立链表/建树,这里以单链表和二叉树为例说明如何在笔试题的时候自己建立链表和树
建立链表
首先,需要写出链表的数据结构
function ListNode(val, next){
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
之后,通常给出的初始建立数组应该是这样的/字符串,如果是字符串自己使用split和replaceAll截取一下(有的时候可能会有多余的空格)
[1, 2, 4, 5, 6]
function structLink(arr){
const dummyHead = new ListNode(0);
const cur = dummyHead;
for(let i = 0; i < arr.length; i++){
const curNode = new ListNode(arr[i]);
cur.next = curNode;
cur = curNode;
}
return dummyHead.next;
}
这里我使用vscode本地进行测试,结果如下
建树
其实建树的过程就是二叉树的反序列化
首先写出二叉树的数据结构
function TreeNode(val, left, right){
this.val = val === undefined ? 0 : val;
this.left = this.right = null;
}
建树这里考虑是前序遍历之后的结果,这里我使用测试用例
[1,2,3,null,null,4,5]
function buildTree(arr){
if(!arr.length) return null;
const root = new TreeNode(arr[0]);
const que = [root];
let idx = 1;
while(que.length){
let node = que.shift();
node.left = null;
node.right = null;
if(arr[idx] != null){
node.left = new TreeNode(arr[idx]);
que.push(node.left);
}
idx++;
if(arr[idx] != null){
node.right = new TreeNode(arr[idx]);
que.push(node.right);
}
idx++;
}
return root;
}
这里也是使用本地进行测试,