Lowest Common Ancestor of a Binary TreeWhat does the binary tree's lowest common ancestor represent?The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we are looking for the LCA. As a result, the common ancestor of nodes n1 and n2 that is placed the furthest from the root is the LCA of a binary tree containing nodes n1 and n2. LCA (Lowest Common Ancestor) application:The gap between pairs of nodes in a tree can be computed as the distance from the root to n1 plus the distance from the root to n2 minus twice the distance from the root to their lowest common ancestor. Example:Approach
Program in C++:Recursive Approach Using single Traversal Time complexity: O(n) Space complexity: O(n) Function to print LCA: Input: Output: 3 Iterative ApproachUsing Double Traversal and finding path for node p and q respectively than comparing their path to find LCA. Complexity Time complexity: O(n)+O(n) Space complexity: O(n)+O(n) Function to print LCA: Input: Output: 3 Function to print LCA in Python:Input: Output: 3 Function to print LCA in Java:Input: Output: 3
Next TopicTop View of a Binary Tree
