希望有人能帮助我了解这门课是如何运作的。
我目前正在 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。
只是不确定数组如何转换成那个
Thanks!
尝试将节点一一添加,然后执行二叉树操作