我这样实现满二叉树,字节面试官都无语了

Front

事情是这样的,最近面字节的是时候,面试官让我实现一个满二叉树。

先说一下什么是满二叉树,就是每添加一个节点都从左到右放入,比如我依次添加[1,2,3,4,5],那么就会形成下面的一颗满二叉树。

思路

我的思路是通过一个数组去维护所以添加的node,这个数组就叫nodeList吧。因为每个二叉树的节点都只有两个左和右,我会用一个下标index来记录当前需要添加子节点的node,然后让每个node产生引用关系,最后返回nodeList第一个节点就是我们需要的那颗完整的满二叉树。

js 复制代码
class Node {
    constructor(value) {
        this.value = value
        this.left = null
        this.right = null
    }
}


class FullTree {

    constructor() {

        console.log('init')

    }

    nodeList = []

    index = 0

    insertNode = (value) => {

        if (this.nodeList.length === 0) {

            this.nodeList.push(new Node(value))

        } else {

            let { left, right } = this.nodeList[this.index]

            this.nodeList.push(new Node(value))

            if (!left) return this.nodeList[this.index].left = this.nodeList[this.nodeList.length - 1]

            if (!right) {

                this.nodeList[this.index].right = this.nodeList[this.nodeList.length-1]

                this.index += 1

            }

        }

    }

    root = () => this.nodeList[0]

}

let tree = new FullTree()

tree.insertNode(1)
tree.insertNode(2)
tree.insertNode(3)
tree.insertNode(4)
tree.insertNode(5)


console.log(tree.root())

用数组维护二叉树的好处了是,我可以很轻松的找到"它的最大或者最小节点,也可以很轻松的删除指定的某节点",这也是当时面试官还提的两个要求,这里就不写了,有兴趣的同学自己去思考一下。

End

如果你有其他实现的方案,可以写在评论区中,show me your code !!!

相关推荐
Z兽兽6 小时前
React@18+Vite项目配置env文件
前端·react.js·前端框架
SuniaWang6 小时前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题六:《Vue3 前端开发实战:打造企业级 RAG 问答界面》
java·前端·人工智能·spring boot·后端·spring·架构
A_nanda7 小时前
根据AI提示排查vue前端项目
前端·javascript·vue.js
happymaker06267 小时前
web前端学习日记——DAY05(定位、浮动、视频音频播放)
前端·学习·音视频
~无忧花开~7 小时前
React状态管理完全指南
开发语言·前端·javascript·react.js·前端框架
LegendNoTitle8 小时前
计算机三级等级考试 网络技术 选择题考点详细梳理
服务器·前端·经验分享·笔记·php
@大迁世界8 小时前
1.什么是 ReactJS?
前端·javascript·react.js·前端框架·ecmascript
BJ-Giser9 小时前
Cesium 基于EZ-Tree的植被效果
前端·可视化·cesium
王码码203510 小时前
Flutter for OpenHarmony:Flutter 三方库 algoliasearch 毫秒级云端搜索体验(云原生搜索引擎)
android·前端·git·flutter·搜索引擎·云原生·harmonyos
发现一只大呆瓜10 小时前
深入浅出 AST:解密 Vite、Babel编译的底层“黑盒”
前端·面试·vite