public void add(BTreeNode node,int item){-baidu 1point3acres
if (item < node.val) {
if (node.left == null) {
node.left = new BTreeNode(null, item, null);
} else {
add(node.left, item);. check 1point3acres for more.
}
} else if (item > node.val) {
if (node.right == null) {
node.right = new BTreeNode(null, item, null);
} else {
add(node.right, item);
}. Χ
}.--
}. .и
. 1point 3 acres
public int bstDistance(int[] values, int n, int node1, int node2){
int l1=Pathlength(root,node1);. check 1point3acres for more.
int l2=Pathlength(root,node2);
int lcaVal = findLCA(root, node1, node2).val;
int lcaDistance = Pathlength(root, lcaVal);
return (l1 + l2) - 2 * lcaDistance;.google и
}
..
public int Pathlength(BTreeNode root, int n) {
return PathlengthHelp(root,n)-1;
}
public int PathlengthHelp(BTreeNode root, int n) {
if (root != null) {
int x = 0;
if ((root.val == n) || (x = PathlengthHelp(root.left, n)) > 0. ----
|| (x = PathlengthHelp(root.right, n)) > 0) {
return x+1 ;
}
return 0;
}
return 0;
}
public BTreeNode findLCA(BTreeNode root, int node1, int node2) {
if (root != null) {.google и
if (root.val == node1 || root.val == node2) {
return root;
}
BTreeNode left = findLCA(root.left, node1, node2);
BTreeNode right = findLCA(root.right, node1, node2);
if (left != null && right != null) {
return root;
}
if (left != null) {
return left;
}
if (right != null) {
return right;
}
}
return null;
}
public static void main(String[] args) {.
BSTDistance test=new BSTDistance();. Χ
int values[]={5,6,3,1,2,4};
test.CreateBST(values,6);.
BTreePrinter.printNode(test.root);
int res=test.bstDistance(values, 6, 1, 2);
System.out.println(res);
}