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

做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 @   樊顺  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
历史上的今天:
2018-11-17 3分钟简单了解 prototype 和 __proto__
2018-11-17 3分钟了解HTTP的基础概念
点击右上角即可分享
微信分享提示