题解 | #二叉搜索树的最近公共祖先#
二叉搜索树的最近公共祖先
http://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f
记录路径,再比较
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param p int整型
* @param q int整型
* @return int整型
*/
function lowestCommonAncestor( root , p , q ) {
// write code here
let pPath = []
let qPath = []
let tempRoot = root
while (root != null) {
if (p > root.val) {
pPath.push(root.val)
root = root.right
} else if (p < root.val) {
pPath.push(root.val)
root = root.left
} else {
pPath.push(root.val)
break
}
}
root = tempRoot
while (root != null) {
if (q > root.val) {
qPath.push(root.val)
root = root.right
} else if (q < root.val) {
qPath.push(root.val)
root = root.left
} else {
qPath.push(root.val)
break
}
}
for (let i = pPath.length - 1; i >= 0; i--) {
for (let j = qPath.length - 1; j >= 0; j--) {
if (pPath[i] == qPath[j]) {
return pPath[i]
}
}
}
}
module.exports = {
lowestCommonAncestor : lowestCommonAncestor
};