MemotivaLeetCode Patterns Flashcards: Trees, DFS, BFS, Traversals, BST Properties

How do you find the lowest common ancestor in a binary tree?

LeetCode Patterns Flashcards: Trees, DFS, BFS, Traversals, BST Properties

Аудио-карточка · 0:31

Nortren·

How do you find the lowest common ancestor in a binary tree?

0:31

The lowest common ancestor, or LCA, is the deepest node that has both target nodes as descendants, where a node can be its own ancestor. Use DFS: if the current node is null or equals either target, return the current node. Recursively search left and right subtrees. If both recursive calls return non-null, the current node is the LCA because one target is in each subtree. If only one returns non-null, propagate that result upward. For a BST, the solution is simpler: if both targets are smaller, go left; if both are larger, go right; otherwise the current node is the LCA.
neetcode.io