var lowestCommonAncestor = function (root, p, q) {
const pPath = findPath(root, p)
const qPath = findPath(root, q)
for (let i = pPath.length - 1; i >= 0; i--) {
for (let j = qPath.length - 1; j >= 0; j--) {
if (pPath[i].val === qPath[j].val) {
return pPath[i]
}
}
}
};
function findPath(root, target, path) {
path = path || []
if (!root) {
return null
}
path.push(root)
if (root.val === target.val) {
return path
}
const left = findPath(root.left, target, path.slice(0))
const right = findPath(root.right, target, path.slice(0))
return left || right
}
var lowestCommonAncestor = function (root, p, q) {
let map = new Map()
function recordParent(parent, cur) {
if (!cur) {
return
}
map.set(cur, parent)
recordParent(cur, cur.left)
recordParent(cur, cur.right)
}
recordParent(null, root)
let pPath = []
let cur = p
while (cur) {
pPath.unshift(cur.val)
cur = map.get(cur)
}
let qPath = []
cur = q
while (cur) {
qPath.unshift(cur.val)
cur = map.get(cur)
}
console.log(pPath, qPath)
for (let i = pPath.length - 1; i >= 0; i--) {
for (let j = qPath.length - 1; j >= 0; j--) {
if (pPath[i].val === qPath[j].val) {
return pPath[i]
}
}
}
}
var lowestCommonAncestor = function (root, p, q) {
let map = new Map()
function recordParent(parent, cur) {
if (!cur) {
return
}
map.set(cur, parent)
recordParent(cur, cur.left)
recordParent(cur, cur.right)
}
recordParent(null, root)
let pPath = []
let cur = p
while (cur) {
pPath.unshift(cur.val)
cur = map.get(cur)
}
let pVisitedMap = new Map()
while (p) {
pVisitedMap.set(p, true)
p = map.get(p)
}
while (q) {
if (pVisitedMap.has(q)) {
return q
}
q = map.get(q)
}
}