LeetCode 1644: Lowest Common Ancestor of a Binary Tree II
Problem Description
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
:
Solutions
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;
}
}
Loading editor...