1650. (LCA) Lowest Common Ancestor of a Binary Tree III

้€™้กŒ่ทŸๅ‰ๅ…ฉ้กŒไธๅŒ่™•ๆ˜ฏ.., node ๆœฌ่บซๆœ‰ parent info,

่€Œไธ”ๆฒ’ๆœ‰ root input, ๆ‰€ไปฅ่ฆๅˆฉ็”จ parent ไพ†ๆ‰พ

has parent info, use hashset to stroe parent info

because this question gives parent Node

so put p's all parent Nodes into a set<>

then check all q's all parents are in set? if find, it's LCA!

time: O(h), worst case is from leaf to root, is tree's height

space: O(h), same

ๅ› ็‚บๆœ‰ parent, ๆ‰€ไปฅ่ทŸไน‹ๅ‰็š„ๆฆ‚ๅฟต้›ทๅŒ, ๅฆ‚ๆžœ็”จๆšดๅŠ›ๆณ•็š„ๆฆ‚ๅฟตๅŽปๆƒณ(ไน‹ๅ‰ๆœ‰ๆๅˆฐ,

LCA ๆœƒๅ‡บ็พๅพž p ๅพ€ไธŠ, q ๅพ€ไธŠ, ไบคๆœƒไน‹่™•

ๆ‰€ไปฅๅฏไปฅๅ…ˆๆŠŠ p ๅพ€ไธŠ็š„ ่ทฏๅพ‘๏ผˆparent ่ทฏๅพ‘)่จ˜่ตทไพ†, q ๅพ€ไธŠ็š„ ่ทฏๅพ‘, ็›ดๆŽฅๅŽปๆฏ”ๅฐ, ้‚ฃๆ‰พๅˆฐๅฐฑๆ˜ฏ LCA

class Solution {
    public Node lowestCommonAncestor(Node p, Node q) {
        Set<Node> set = new HashSet<>();
        Node curr = p;
        while (curr != null) {
            set.add(curr);
            curr = curr.parent;
        }
        curr = q;
        while (curr != null) {
            if (set.contains(curr)) {
                return curr;
            }
            curr = curr.parent;
        }
        return null;
    }
}

Last updated