【问题标题】:Explanation of class Definition for Binary Trees in leetcodeleetcode 类 Definition for Binary Trees 的解释
【发布时间】:2023-02-16 22:32:21
【问题描述】:

希望有人能帮助我理解这门课是如何运作的。 我目前正在 udemy 学习 javascript 算法,他们解释如何在二叉树中执行所有操作的方式与 leetcode 显示的略有不同。

在课程中,树的定义与leetcode相同或非常相似:

class Node {
    constructor(value){
        this.value = value;
        this.left = null;
        this.right = null;
    }
} 

class BinarySearchTree {
    constructor(){
        this.root = null;
    }
}

但是,在执行任何其他操作之前,这些值首先作为节点插入:

insert(value){
        var newNode = new Node(value);
        if(this.root === null){
            this.root = newNode;
            return this;
        }
        var current = this.root;
        while(true){
            if(value === current.value) return undefined;
            if(value < current.value){
                if(current.left === null){
                    current.left = newNode;
                    return this;
                }
                current = current.left;
            } else {
                if(current.right === null){
                    current.right = newNode;
                    return this;
                } 
                current = current.right;
            }
        }
    }

在 Leetcode 上,值作为数组传递,这让我有点不爽:

二叉树节点的定义。

* function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }

* @param {TreeNode} root
 * @return {number}

查看用于查找最大深度的简单解决方案:

var maxDepth = function(root) {
     if(!root) return 0;
    
    return Math.max(maxDepth(root.left) , maxDepth(root.right) ) +1
};

给定数组 root = [3,9,20,null,null,15,7],

我们怎么知道root.left是9,root.right是20。那么下一层,root.left.left是null,root.left.right是null。那么root.right.left就是15,root.right.right就是7。

只是不确定数组如何转化为

谢谢!

尝试一个一个地添加节点然后执行二叉树操作

【问题讨论】:

    标签: javascript algorithm binary-tree


    【解决方案1】:

    在 Leetcode 上,值作为数组传递

    这是一种误解。

    值不作为数组传递。您的函数获取 Node 的实例作为参数(或 null)。 LeetCode 让你指定以一种 JSON 格式输入,但这只是 LeetCode 在调用您的方法之前首先将其转换为基于 Node 的树的文本。

    文本输入遵循一种面包优先遍历它应该表示的树。所以[3,9,20,null,null,15,7]代表这棵树:

                   3
                  / 
                 9   20
                    /  
                  15    7
    

    两次出现null 表示值为 9 的节点没有左孩子或右孩子。

    【讨论】:

      【解决方案2】:

      该数组表示通常称为“堆”。数组中的位置表示基于索引的树中的节点。位置上的节点n在职位上有孩子2n+12n+2.位置为零的节点是根。

      根的孩子在2x0+12x0+2, 数组中的位置 1 和 2。位置 1 的根的左孩子是 9,它的孩子在位置 3 和 4,两个 null 值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-30
        • 2020-04-24
        • 1970-01-01
        • 2023-02-08
        • 2022-06-15
        • 2019-11-11
        • 2019-06-08
        • 1970-01-01
        相关资源
        最近更新 更多