题解 | #在二叉树中找到两个节点的最近公共祖先#
在二叉树中找到两个节点的最近公共祖先
https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
/*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) * } * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param o1 int整型 * @param o2 int整型 * @return int整型 */ export function lowestCommonAncestor(root: TreeNode, o1: number, o2: number): number { if(root == null){ return null } if(root.val == o1 || root.val == o2){ return root.val } const left = lowestCommonAncestor(root.left,o1,o2) const right = lowestCommonAncestor(root.right,o1,o2) if(left ==null&&right == null)return null if(left !== null && right !== null)return root.val return left ? left:right }