ListNode and TreeNode can only be used to restore test cases to other compilation tools, so sort out some methods and use them directly when needed.

Array list

Prerequisite: Create a class for linked list nodes

Class ListNode{constructor(val,next){this.val = (val===undefined? 0 : val); this.next = (next===undefined ? null : next); }} /** * @param {array} * @return {ListNode} */ / convert array to list const chainList = (arr) => {let head = new ListNode(arr[0]); let tail = head; for (let i = 1; i < arr.length; i++) { let node = new ListNode(arr[i]); tail.next = node; tail = node; } return head; }Copy the code

In problem 2 (add two numbers)

Browser debugging is also very helpful in understanding the list structure defined by Lykoli.

Turn the array tree

Prerequisite: Create a chain-stored tree node class

Constructor (val,left,right){this.val = (val===undefined? undefined : val); this.left = (left===undefined ? null : left); this.right = (right===undefined ? null : Const BinaryTree = (arr) => {if(arr. Length <1){return new TreeNode}else{let root = new TreeNode(arr[0]) let nowRoot = root for(let i = 1; i < arr.length; i++){ if(2*i<=arr.length){ nowRoot.left = new TreeNode(arr[2*i-1]) } if(2*i+1<=arr.length){ nowRoot.right = new TreeNode(arr[2*i]) } if(i%2==0){ nowRoot = nowRoot.right }else{ nowRoot = nowRoot.left } } return root } }Copy the code

Applied in #### 94. Middle order traversal of binary trees

Building a stack

Const createStack = () => {class Stack{constructor(){this.top = 0; this.stores = []; } push(item){ this.top++; return this.stores.push(item) } pop(){ this.top-- return this.stores.pop() } peer(){ return this.stores[this.stores.length-1] } isEmpty(){ return this.top == 0; } } return new Stack(); }Copy the code

Reference: JavaScript data structures and algorithms (linked list) easy to debug tool class (force button)