我刚刚开始学习二进制搜索树之类的东西,我试图找到目标到二进制搜索树中每个节点的距离。在数据结构方面,使用JavaScript确实非常困难,而且很难找到示例。非常感谢您的帮助!
7
/ \
4 8
/ \ / \
3 6
/
2
for the traget of 6, my output should be {7: 2, 4:1, 3:2, 2:3, 8:3, 6:0}
到目前为止我所拥有的:
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
const calculate = (node, target) => {
let counter = 0;
const nodesAndThereDistances = {}
if (!node) {
return null;
}
const inner = (node, target) => {
if (!node) {
return null;
}
if (node.data !== target) {
counter++;
nodesAndThereDistances[node.data] = counter;
if (node.left, target) {
inner(node.left, target)
}
if (node.right, target) {
inner(node.right, target)
}
} else {
return nodesAndThereDistances;
}
}
inner(node, target)
return nodesAndThereDistances;
}
calculate(node1, 6)