236. Lowest Common Ancestor of a Binary Tree

54 阅读1分钟

236. Lowest Common Ancestor of a Binary Tree

解题思路

  1. 对于一个有效的节点,符合左右节点val是有效节点 或者 node 本身是有效节点 即 isValidLeft || isValidRight || (ans.val === p.val || ans.val === q.val),这个是对每个节点是否有效的判断条件
  2. 那么如果一个有效的 ancestor,符合 左右节点都是有效节点 或者 本身val符合目标值 且 左右任意节点val符合目标值即是我们要找的 Lowest Common Ancestor of a Binary Tree,即
bothChildValid || ansAndOneOfChildValid
  1. 那么进行深度递归,递归基是 ans === null
const isValidLeft = iter(ans.left)
const isValidRight = iter(ans.right)
  1. 在做单个节点是否有效前判断节点本身是否是有效的 ancestor,如果是直接返回 ans 即可,即
if(bothChildValid || ansAndOneOfChildValid) {
    return ans
}

代码

/**
 * 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) {
    const iter = (ans) => {
        if(ans === null) return false
        // iter to bottom 
        const isValidLeft = iter(ans.left)
        const isValidRight = iter(ans.right)

        // left node and right is valid
        const bothChildValid = isValidLeft && isValidRight
        // ans is equal p or q and left or right is valid
        const ansAndOneOfChildValid = (ans.val === q.val || ans.val === p.val) && (isValidRight || isValidLeft)
        if(bothChildValid || ansAndOneOfChildValid) {
            return ans
        } 

        return isValidLeft || isValidRight || (ans.val === p.val || ans.val === q.val)
    }
    return iter(root)
};