题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
记录一个错误:
由于Queue中存的是Integer类型,而Integer类型值在超过127之外就是不相同的(值相等但是对象不相同!),所以这里比较相等时一定要转化为int类型,不然就用equals,千万不要图省力把许多步合成一步!
public int lowestCommonAncestor (TreeNode root, int p, int q) {
// write code here
Queue<Integer>queue1=new LinkedList<>();
Queue<Integer>queue2=new LinkedList<>();
TreeNode cur=root;
while(cur.val!=p){
queue1.offer(cur.val);
if(cur.val>p)
cur=cur.left;
else if(cur.val<p)
cur=cur.right;
}
queue1.offer(cur.val);
cur=root;
while(cur.val!=q){
queue2.offer(cur.val);
if(cur.val>q)
cur=cur.left;
else if(cur.val<q)
cur=cur.right;
}
queue2.offer(cur.val);
int par=0;
for(int i:queue1)
System.out.println(i);
for(int i:queue2)
System.out.println(i);
while(queue1.peek()==queue2.peek()){
par=queue1.poll();
System.out.println(par);
System.out.println(queue2.poll());
}
return par;
}
}
查看11道真题和解析
