不准访问
- 积分
- 376
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-10-18
- 最后登录
- 1970-1-1
|
大家好 我换了个马甲 注册,又拿了个社招OA
又挂了,
第一题valid patheless 秒过 ,case全过
第二题,distance between two node 。在我自己的eclipse跑没问题,结果测试case死活有问题。.--
我也认了,放上代码。小伙伴们帮忙看看哪里错了?
public class BSTDistance {
private BTreeNode root;
public void CreateBST(int[] values,int n){
for(int i=0;i<n;i++){. 1point3acres.com
add(values[i]);
}
}
-baidu 1point3acres
public void add(int item){
if(root==null){
root=new BTreeNode(null,item,null);
}else{
add(root,item);.--
}.
}
.google и
public void add(BTreeNode node,int item){ ..
if (item < node.val) {
if (node.left == null) {
node.left = new BTreeNode(null, item, null);
} else {
add(node.left, item);
}
} else if (item > node.val) {
if (node.right == null) {
node.right = new BTreeNode(null, item, null);
} else {
add(node.right, item);
}
}
}
-baidu 1point3acres
public int bstDistance(int[] values, int n, int node1, int node2){
int l1=Pathlength(root,node1);
int l2=Pathlength(root,node2);
int lcaVal = findLCA(root, node1, node2).val;
int lcaDistance = Pathlength(root, lcaVal);
return (l1 + l2) - 2 * lcaDistance;. Χ
}
public int Pathlength(BTreeNode root, int n) {
return PathlengthHelp(root,n)-1;
}
. 1point3acres
public int PathlengthHelp(BTreeNode root, int n) {
if (root != null) {. Waral dи,
int x = 0;
if ((root.val == n) || (x = PathlengthHelp(root.left, n)) > 0
|| (x = PathlengthHelp(root.right, n)) > 0) {
return x+1 ;
}.google и
return 0;
}. From 1point 3acres bbs
return 0;
}
public BTreeNode findLCA(BTreeNode root, int node1, int node2) {
if (root != null) {
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) {. check 1point3acres for more.
return root;
}. 1point 3acres
if (left != null) {
return left;
}
if (right != null) {. 1point3acres.com
return right;
}
}
return null;
}
public static void main(String[] args) {
BSTDistance test=new BSTDistance();
int values[]={5,6,3,1,2,4};. check 1point3acres for more.
test.CreateBST(values,6);
BTreePrinter.printNode(test.root);
int res=test.bstDistance(values, 6, 1, 2);
System.out.println(res);.google и
} |
|