Skip to content

Commit

Permalink
feat: 二叉树最近公共祖先
Browse files Browse the repository at this point in the history
  • Loading branch information
sl1673495 committed Jun 11, 2020
1 parent 5aef9dc commit a016618
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions 二叉树/二叉树的最近公共祖先.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
let T = require("../工具/二叉树")

let lowestCommonAncestor = function (root, p, q) {
let findAndCreate = (node, target, depth) => {
if (node !== target) {
let findInLeft
if (node.left) {
node.left.parent = node
findInLeft = findAndCreate(node.left, target, depth + 1)
}

if (findInLeft) {
return findInLeft
} else {
if (node.right) {
node.right.parent = node
return findAndCreate(node.right, target, depth + 1)
}
}
} else {
return {
depth,
node,
}
}
}

let findP = findAndCreate(root, p, 0) || {}
let findQ = findAndCreate(root, q, 0) || {}

let cur = findP.depth > findQ.depth ? findQ.node : findP.node

while (!(isAncestor(cur, p) && isAncestor(cur, q))) {
cur = cur.parent
}

return cur
}

function isAncestor(node, target) {
if (!node) {
return false
}
if (node !== target) {
return !!(isAncestor(node.left, target) || isAncestor(node.right, target))
} else {
return true
}
}

let l
let r
let t = new T(3)
t.left = l = new T(5)
t.right = r = new T(1)

console.log(lowestCommonAncestor(t, l, r))

0 comments on commit a016618

Please sign in to comment.