在 JavaScript 中查找二叉搜索树中的最小绝对差
我们需要编写一个JavaScript函数,该函数接收BST的根,该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(){ //二叉搜索树的根 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输出结果 控制台中的输出将是-
1