力扣刷题一些实用方法(数组转链表,树...)

781 阅读1分钟

力扣刷题,当遇到链表和树的问题的时候,需要用到官方提供的ListNode和TreeNode,没开会员只能把测试用例还原到其它编译工具里,因此整理一些方法,需要的时候直接拿来用。

数组转链表

前提:创建一个链表节点的类

// 链表节点
class ListNode{
    constructor(val,next){
        this.val = (val===undefined ? 0 : val);
        this.next = (next===undefined ? null : next);
    }
}
/**
 * @param {array} 
 * @return {ListNode}
 */
// 将数组转化为链表
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;
}

应用在第2题(两数相加)

1638329026096_4181DBEE-C001-4a33-99D6-9E8EA5D0E6E1.png 用浏览器调试也很对于我们理解力扣里定义的链表结构很有帮助。

数组转树

前提:创建一个链式存储的树节点的类

// 树
class TreeNode{
    constructor(val,left,right){
        this.val = (val===undefined ? undefined : val);
        this.left = (left===undefined ? null : left);
        this.right = (right===undefined ? null : right)
    }
}
// 数组转化为二叉树
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
    }
}

应用在第#### 94. 二叉树的中序遍历

1638338558877_D4B10D7D-A514-44b2-A64A-8F8FB3620A09.png

构建一个栈

// 构建一个栈
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();
}

参考:JavaScript数据结构与算法(链表) 方便调试的工具类(力扣)