以 236. Lowest Common Ancestor of a Binary Tree 为例:
// Define a simple binary tree node structure
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
// Create a binary tree
// 3
// / \
// 5 1
// / \ / \
// 6 2 0 8
// / \
// 7 4
const root = new TreeNode(3);
root.left = new TreeNode(5);
root.right = new TreeNode(1);
root.left.left = new TreeNode(6);
root.left.right = new TreeNode(2);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(8);
root.left.right.left = new TreeNode(7);
root.left.right.right = new TreeNode(4);
// Nodes for which we want to find the LCA
const p = root.left; // Node with value 5
const q = root.left.right.right; // Node with value 4
var lowestCommonAncestor = function (root, p, q) {
function dfs(root, q, p) {
if (root === q || root === p || root === null) return root;
let left = dfs(root.left, q, p);
let right = dfs(root.right, q, p);
if (left !== null && right !== null) return root;
else if (left !== null && right === null) return left;
else if (left === null && right !== null) return right;
else return null;
}
return dfs(root, q, p);
};
// Call the lowestCommonAncestor function
const lca = lowestCommonAncestor(root, p, q);
// Output the result
console.log(
`The lowest common ancestor of nodes ${p.val} and ${q.val} is node with value ${lca.val}.`
);
// TreeNode constructor
class TreeNode {
constructor(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
// Create a binary tree
// 3
// / \
// 5 1
// / \ / \
// 6 2 0 8
// / \
// 7 4
const root = new TreeNode(
3,
new TreeNode(
5,
new TreeNode(6),
new TreeNode(2, new TreeNode(7), new TreeNode(4))
),
new TreeNode(1, new TreeNode(0), new TreeNode(8))
);
const p = root.left; // Node with value 5
const q = root.left.right.right; // Node with value 4
// Lowest Common Ancestor function
var lowestCommonAncestor = function (root, p, q) {
function dfs(root, q, p) {
if (root === q || root === p || root === null) return root;
let left = dfs(root.left, q, p);
let right = dfs(root.right, q, p);
if (left !== null && right !== null) return root;
else if (left !== null && right === null) return left;
else if (left === null && right !== null) return right;
else return null;
}
return dfs(root, q, p);
};
// Find the LCA
const lca = lowestCommonAncestor(root, p, q);
console.log(
`The lowest common ancestor of nodes ${p.val} and ${q.val} is node ${lca.val}.`
);