题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param o1 int整型 * @param o2 int整型 * @return int整型 */ function core(root, o1, o2) { if (!root) { return [-1, false, false]; } let current = [root.val, o1 == root.val, o2 == root.val]; let left = core(root.left, o1, o2); let right = core(root.right, o1, o2); let is1 = current[1] || left[1] || right[1]; let is2 = current[2] || left[2] || right[2]; let value = -1; if ((left[1] && left[2]) || (right[1] && right[2])) { // 说明早已经找到了则不修改value value = left[0] != -1 ? left[0] : right[0]; console.log(value) } else { value = current[0]; } return [value, is1, is2]; } function lowestCommonAncestor(root, o1, o2) { // write code here let res = core(root, o1, o2); return res[0]; } module.exports = { lowestCommonAncestor: lowestCommonAncestor, };