鉴于二叉搜索树,我需要编写一个函数来查找2个节点之间的距离。我认为我对此很满意,但似乎无法正常工作。如果要搜索树同一侧上的节点之间的距离。不确定如何解决此问题。任何提示将非常感谢。下面是我到目前为止的代码。我的代码使用Javascript。
function Node(val){
this.value = val;
this.left = null;
this.right = null;
}
function BinarySearchTree(value) {
this.root = null;
};
BinarySearchTree.prototype.push = function(val){
var root = this.root;
if(!root){
this.root = new Node(val);
return;
}
var currentNode = root;
var newNode = new Node(val);
while(currentNode){
if(val < currentNode.value){
if(!currentNode.left){
currentNode.left = newNode;
break;
}
else{
currentNode = currentNode.left;
}
}
else{
if(!currentNode.right){
currentNode.right = newNode;
break;
}
else{
currentNode = currentNode.right;
}
}
}
}
BinarySearchTree.prototype.levelOfNode =
function(root, key, level){
if(root === null){
return -1;
}else if(root.value === key){
return level;
}
let l = this.levelOfNode(root.left, key, level+1)
if (l!== -1){
return l;
}
return this.levelOfNode(root.right, key, level +1)
}
BinarySearchTree.prototype.lca = function(root, n1, n2){
if(!root) return;
var val = root.value;
if(n1<val && n2<val){
return lca(root.left, n1, n2);
}
if(n1>val && n2>val){
return lca(root.right, n1, n2);
}
return this.root;
}
BinarySearchTree.prototype.findDistance = function(root, n1, n2){
let lcaValue = this.lca(root, n1, n2);
let l1 = this.levelOfNode(lcaValue, n1, 0);
let l2 = this.levelOfNode(lcaValue, n2, 0);
return l1 + l2;
}
let tree = new BinarySearchTree();
tree.push(4);
tree.push(8);
tree.push(9);
tree.push(11);
tree.push(3);
tree.findDistance(4,8,11);
答案 0 :(得分:2)
虽然有一棵看起来像
的树4 3 8 9 11
您可以从根目录获取每个目标的路径,并且
[4, 8] [4, 8, 9, 11]
消除所有公共节点。然后检查一个路径数组是否为空,并获取另一个路径的长度。
如果有两个非空数组,则可以将两个数组的长度相加,例如
[4, 3] [4, 8, 9]
消除公共节点后
[3] [8, 9]
然后添加两个长度
1 + 2 = 3