LeetCode 236: Lowest Common Ancestor of a Binary Tree Solution

Master LeetCode problem 236 (Lowest Common Ancestor of a Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

236. Lowest Common Ancestor of a Binary Tree

Problem Explanation

Explanation:

To find the lowest common ancestor (LCA) of two nodes in a binary tree, we can use a recursive approach starting from the root. The idea is to recursively search for the nodes p and q in the left and right subtrees. If both nodes are found in separate subtrees, then the current node is the LCA. If both nodes are found in the same subtree, we continue the search in that subtree.

Algorithm:

  1. If the current node is null or equal to either p or q, return the current node.
  2. Recursively search for p and q in the left subtree.
  3. Recursively search for p and q in the right subtree.
  4. If both p and q are found in separate subtrees, return the current node as LCA.
  5. If both p and q are found in the same subtree, return the LCA from that subtree.

Time Complexity: O(N) - where N is the number of nodes in the tree. Space Complexity: O(N) - recursive stack space.

:

Solution Code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) return root;

    TreeNode left = lowestCommonAncestor(root.left, p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);

    if (left != null && right != null) return root;
    return left != null ? left : right;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 236 (Lowest Common Ancestor of a Binary Tree)?

This page provides optimized solutions for LeetCode problem 236 (Lowest Common Ancestor of a Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 236 (Lowest Common Ancestor of a Binary Tree)?

The time complexity for LeetCode 236 (Lowest Common Ancestor of a Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 236 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 236 in Java, C++, or Python.

Back to LeetCode Solutions