首发于 语雀文档@blueju
代码:
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function lowestCommonAncestor(root, p, q) {const dfs = (root, p, q) => {if (root === null) return rootif (root === p || root === q) return rootconst left = dfs(root.left, p, q)const right = dfs(root.right, p, q)if (left == null && right == null) return null;if (left == null) return right;if (right == null) return left;if (left != null && right != null) return root}return dfs(root, p, q)};
