【发布时间】: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