在 JavaScript 中的二叉搜索树中找出最小绝对差
我们要求编写一个 JavaScript 函数,采用包含此类数值数据的 BST 的根,例如:
1 \ 3 / 2
该函数应返回树中任意两个节点之间的最小绝对差。
例如:
对于以上树,输出应该是:
const output = 1;
这是因为 |1 - 2| = |3 - 2| = 1
示例
代码如下:
class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
};
};
class BinarySearchTree{
constructor(){
// root of a binary seach tree
this.root = null;
}
insert(data){
var newNode = new Node(data);
if(this.root === null){
this.root = newNode;
}else{
this.insertNode(this.root, newNode);
};
};
insertNode(node, newNode){
if(newNode.data < node.data){
if(node.left === null){
node.left = newNode;
}else{
this.insertNode(node.left, newNode);
};
} else {
if(node.right === null){
node.right = newNode;
}else{
this.insertNode(node.right,newNode);
};
};
};
};
const BST = new BinarySearchTree();
BST.insert(1);
BST.insert(3);
BST.insert(2);
const getMinimumDifference = function(root) {
const nodes = [];
const dfs = (root) => {
if(root) {
dfs(root.left);
nodes.push(root.data);
dfs(root.right);
};
};
dfs(root);
let result = nodes[1] - nodes[0];
for(let i = 1; i < nodes.length - 1; i++) {
result = Math.min(result, nodes[i + 1] - nodes[i]);
};
return result;
};
console.log(getMinimumDifference(BST.root));输出
控制台中的输出将是:
1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP