给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
递归:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if (!root || root.val === p.val || root.val === q.val) return root
let left = lowestCommonAncestor(root.left, p, q)
let right = lowestCommonAncestor(root.right, p, q)
return left === null ? right : right === null ? left : root
}
栈:
var lowestCommonAncestor = function(root, p, q) {
let parent = new Map(), stack = [], res = new Set();
parent.set(root, null);
stack.push(root);
while(!parent.has(p) || !parent.has(q)) {
let node = stack.pop();
if (node.left !== null) {
parent.set(node.left, node)
stack.push(node.left)
}
if (node.right !== null) {
parent.set(node.right, node)
stack.push(node.right)
}
}
while(p !== null) {
res.add(p)
p = parent.get(p)
}
while(!res.has(q)) {
q = parent.get(q)
}
return q
}