题解 | #在二叉树中找到两个节点的最近公共祖先#

在二叉树中找到两个节点的最近公共祖先

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 {
    // write code here
    const o1Path = findPath(root, o1)
    const o2Path = findPath(root, o2)
    
    let i = 0
    while (i < Math.min(o1Path.length, o2Path.length)) {
        if (o1Path[i] === o2Path[i]) {
            i++
        } else {
            break
        }
    }

    return o1Path[i - 1]
}

const findPath = (root: TreeNode, value: number): number[] => {
    if (root === null) return []

    if (root.val === value) {
        return [value]
    } else {
        const leftPath = findPath(root.left, value)
        const rightPath = findPath(root.right, value)
        if (leftPath.length > 0) {
            leftPath.unshift(root.val)
            return leftPath
        }

        if (rightPath.length > 0) {
            rightPath.unshift(root.val)
            return rightPath
        }

        return []
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务