题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
http://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
//发现找数字大小规律太乱了,那就找结构规律,反正也要按结构索引
function lowestCommonAncestor( root , p , q ) {
// write code here
let res=[]
let res1=[]
res1.push('t')
res1.push(root)
res.push(res1)
let resp=''
let resq=''
let sum=2
while(res.length!=0){
let p1=res.pop()
if(p1[1].val==p){resp=p1[0];sum--;console.log(resp)}
if(p1[1].val==q){resq=p1[0];sum--;console.log(resq)}
if(sum>0){
if(p1[1].left!=null){
let b=[]
b[0]=p1[0]+'l'
b.push(p1[1].left)
res.push(b)
}
if(p1[1].right!=null){
let b=[]
b[0]=p1[0]+'r'
b.push(p1[1].right)
res.push(b)
}
}
else{break;}
}
let max=resp.length
if(resq.length>resp.length){max=resq.length}
for(let i=0;i<max;i++){
console.log(i)
if(i>resq.length-1||resp[i]!=resq[i]){
if(i==1){return root.val}
let p2=root
for(let j=1;j<i;j++){
if(resp[j]=='l'){
p2=p2.left
}
else if(resp[j]=='r'){
p2=p2.right
}
}
return p2.val
}
}
return null
}
module.exports = {
lowestCommonAncestor : lowestCommonAncestor
};