LeetCode 1644: Lowest Common Ancestor of a Binary Tree II Solution
Master LeetCode problem 1644 (Lowest Common Ancestor of a Binary Tree II), 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.
1644. Lowest Common Ancestor of a Binary Tree II
Problem Explanation
Explanation:
To find the lowest common ancestor (LCA) of two nodes in a binary tree, we can recursively search for the nodes in the left and right subtrees. If either subtree contains both nodes, then the current node must be the LCA. If one node is found in the left subtree and the other in the right subtree, then the current node is the LCA. If both nodes are in the same subtree, we continue the search in that subtree.
Algorithm:
- Start from the root and recursively search for both nodes in the left and right subtrees.
- If either subtree contains both nodes, return the current node as LCA.
- If one node is found in the left subtree and the other in the right subtree, return the current node as LCA.
- If both nodes are in the same subtree, continue the search in that subtree.
Time complexity: O(n) - where n is the number of nodes in the binary tree Space complexity: O(h) - where h is the height of the binary tree
:
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;
} else if (left != null) {
return left;
} else {
return right;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1644 (Lowest Common Ancestor of a Binary Tree II)?
This page provides optimized solutions for LeetCode problem 1644 (Lowest Common Ancestor of a Binary Tree II) 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 1644 (Lowest Common Ancestor of a Binary Tree II)?
The time complexity for LeetCode 1644 (Lowest Common Ancestor of a Binary Tree II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1644 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1644 in Java, C++, or Python.