236. (LCA) Lowest Common Ancestor of a Binary Tree

time: O(n)

space:O(n)

/*
    236. Lowest Common Ancestor of a Binary Tree

    1. ็ต‚ๆญขๆขไปถ
    2. ๆ‰พๅทฆๅญๆจน
    3. ๆ‰พๅณๅญๆจน
    4. ๅฆ‚ๆžœๅœจๅทฆๅณๅญๆจนๆ‰พๅˆฐpq, ไปฃ่กจpqไธ€ๅ€‹ๅœจๅทฆไธ€ๅ€‹ๅœจๅณ, rootๅฐฑๆœƒๆ˜ฏLCS
    5. ๅฆ‚ๆžœๅชๆœ‰ๅœจๆŸไธ€้‚Šๆ‰พๅˆฐ, ไปฃ่กจpqๅœจๅŒไธ€ๅด, ๆ‰€ไปฅLCSๅฐฑๆ˜ฏๆŸไธ€้‚Šๆ‰พๅˆฐ็š„ๆœฌ่บซ็ตๆžœ๏ผˆ้กŒ็›ฎไธญๆœ‰ๆๅˆฐLCSๅฏไปฅๆ˜ฏpๆˆ–qๆœฌ่บซ๏ผ‰

    time complexity: O(n), space complexity: O(n)

 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p.equals(root) || q.equals(root) {
            return root; // 1.terminal condition, find p,q or not find pq => null
        }
        
        TreeNode left = lowestCommonAncestor(root.left, p, q); //2.find left side for p, q
        TreeNode right = lowestCommonAncestor(root.right, p, q); //3.find right side for p, q

        if (left != null && right != null) {
            return root; // 4.if find p,q in left and right side, root is LCS !
        }
        return left != null ? left : right; // 5.if only one side find p or q (it means p,q are all in one side), it's the answer because in question we allow a node to be a descendant of itself
    }
}

ๅฆไธ€ๅ€‹ๆ€่ทฏ, ็”จ count, ๅ…ถๅฏฆไธ€ๆจฃๅ•ฆ...

class Solution {
    TreeNode res = null;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root, p, q);
        return res;
    }
    private int dfs(TreeNode node, TreeNode p, TreeNode q) {
        if (node == null) {
            return 0;
        }
        int left = dfs(node.left, p, q);
        int right = dfs(node.right, p, q);
        int self = (node.val == p.val || node.val == q.val) ? 1 : 0;
        int count = left + right + self;
        if (count == 2 && res == null) {
            res = node;
        }
        return count;
    }
}

Last updated