利用数组构建二叉树(随笔)

做leetcode的时候,看到示例,突然想自己构建一颗树。。
随即自己写了尝试写了一个方法(比较随意)

测试用例:

// example-1
[2,1,3]

// example-2
[2,null,3]

// example-3
[5,3,6,2,4,null,null,1]

测试代码:

/**
 * 树结点
 */
function TreeNode(val) {
   this.val = val;
   this.left = this.right = null;
}

/* ======= 测试函数 ======= */
function test(arr) {
    if (arr.length === 0) {
        return null;
    }
    // 初始化头结点
    const head = arr.shift();
    const root = new TreeNode(head);
    // 剩余元素长度
    const len = arr.length;
    // 维护队列(建树)
    const Q = [root];
    let i = 0;
    while (i < len) {
        // 记录当前层包含的树结点个数
        const size = Q.length;
        // 为现有队列中的每个树结点建立与子结点的关系
        for (let j = 0; j < size; j++) {
            const item = Q.shift();
            const left = new TreeNode(arr[i]);
            const right = new TreeNode(arr[i + 1]);
            item.left = left;
            item.right = right;
            // 如果左子树不为空,推入队列
            if (left !== null) {
                Q.push(item.left);
            }
            // 如果右子树不为空,推入队列
            if (right !== null) {
                Q.push(item.right);
            }
            i += 2;
        }
    }
    // 返回根结点
    return root;
}

 

posted @ 2022-11-17 18:22  樊顺  阅读(30)  评论(0编辑  收藏  举报