우리는 다음과 같은 숫자 데이터를 보유하는 BST의 루트를 취하는 JavaScript 함수를 작성해야 합니다 -
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