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

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 !!!

相关推荐
yqcoder12 分钟前
前端性能优化:如何减少重绘与重排?
前端·性能优化
洋子1 小时前
Yank Note 系列 13 - 让 AI Agent 进入笔记工作流
前端·人工智能
wenzhangli73 小时前
Ooder A2UI 核心架构深度解析:WEB 拦截层的设计与实现
前端·架构
前端百草阁3 小时前
【前端性能优化全链路指南】从开发编写到构建运行的多维度实践
前端·性能优化
神探小白牙4 小时前
eCharts 多系列柱状图增加背景图
javascript·ecmascript·echarts
女生也可以敲代码4 小时前
AI时代下的50道前端开发面试题:从基础到大模型应用
前端·面试
ZhengEnCi4 小时前
M5-markconv自定义CSS样式指南 📝
前端·css·python
IT_陈寒4 小时前
SpringBoot自动配置的坑差点让我加班到天亮
前端·人工智能·后端
xingpanvip4 小时前
星盘接口开发文档:星相日历接口指南
android·开发语言·前端·css·php·lua
@PHARAOH4 小时前
WHAT - GitLens supercharged 插件
前端