# JS生成链表和二叉树

## 链表生成

``````// ListNode构造器，用于创建链表的每个节点
class ListNode {
constructor(val, next) {
this.val = (val == undefined ? 0 : val);
this.next = (next == undefined ? null : next);
}
}

// 生成链表
let head = new ListNode(arr[0]), // 初始化第一个节点作为头节点
for(let i=1; i<arr.length; i++) {
curr.next = new ListNode(arr[i]); // 创建next节点
curr = curr.next; // curr后移一位
}
}

// 调用
console.log(head); // 1 -> 2 -> 3 -> 4``````

``````// 注意，下面这段代码是错误的
curr = obj.next;
for(let i=1; i<arr.length; i++) {
curr = curr.next;
}
return obj
}``````

``ListNode { val: 1, next: null }``

## 二叉树生成

``````// treeNode构造器
class treeNode {
constructor(val, left, right) {
this.val = (val == undefined ? 0 : val);
this.left = (left == undefined ? null : left);
this.right = (right == undefined ? null : right);
}
}

// 生成二叉树
function generateBinarySearchTree(arr) {
let root = new treeNode(arr[0]),
curr = root,
queue = new Array(),
n = 0;
queue.push(curr);
while(queue.length > 0) {
let size = queue.length;
for(let i=0; i<size; i++) {
curr = queue.pop();
curr.left = arr[n+1] ? new treeNode(arr[n+1]) : null;
curr.left && queue.unshift(curr.left); // 如果是null就不入队
n++;

curr.right = arr[n+1] ? new treeNode(arr[n+1]) : null;
curr.right && queue.unshift(curr.right); // 如果是null就不入队
n++;
}
}
return root
}

generateBinarySearchTree([1, 2, 3, 4, 5, 6, 7])``````