Input: root =[6,2,8,0,4,7,9,null,null,3,5], p =2, q =4Output: 2Explanation: The LCA of nodes 2 and 4is2, since a node can be a descendant of itself according to the LCA definition.
publicclassSolution {
private TreeNode root;
private List<TreeNode> path1 =new ArrayList<>();
private List<TreeNode> path2 =new ArrayList<>();
public TreeNode lowestCommonAncestor(int p, int q) {
path1.clear();
path2.clear();
return helper(root, p, q);
}
private TreeNode helper(TreeNode root, int p, int q) {
if (!createPathIfExists(root, p, path1) ||!createPathIfExists(root, q, path2)) {
returnnull; // If either p or q is not present. }
int i;
for (i = 0; i < path1.size() && i < path2.size(); i++) {
if (!path1.get(i).equals(path2.get(i))) {
break;
}
}
return path1.get(i - 1); // Return the lowest common ancestor. }
privatebooleancreatePathIfExists(TreeNode root, int child, List<TreeNode> path) {
if (root ==null) {
returnfalse;
}
path.add(root);
if (root.val== child) {
returntrue;
}
if (createPathIfExists(root.left, child, path) || createPathIfExists(root.right, child, path)) {
returntrue;
}
path.remove(path.size() - 1); // Backtrack if child is not found in this path.returnfalse;
}
publicstaticclassTreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
}
classTreeNode:
def __init__(self, x: int):
self.val = x
self.left: Optional['TreeNode'] =None self.right: Optional['TreeNode'] =NoneclassSolution:
def __init__(self):
self.root: Optional[TreeNode] =None self.path1: List[TreeNode] = []
self.path2: List[TreeNode] = []
deflowestCommonAncestor(self, root: Optional[TreeNode], p: int, q: int) -> Optional[TreeNode]:
self.path1.clear()
self.path2.clear()
ifnot self.createPathIfExists(root, p, self.path1) ornot self.createPathIfExists(root, q, self.path2):
returnNone# If either p or q is not present. i =0while i < len(self.path1) and i < len(self.path2):
if self.path1[i] != self.path2[i]:
break i +=1return self.path1[i -1] if i >0elseNone# Return the lowest common ancestor.defcreatePathIfExists(self, root: Optional[TreeNode], child: int, path: List[TreeNode]) -> bool:
ifnot root:
returnFalse path.append(root)
if root.val == child:
returnTrueif self.createPathIfExists(root.left, child, path) or self.createPathIfExists(root.right, child, path):
returnTrue path.pop() # Backtrack if child is not found in this path.returnFalse
publicclassSolution {
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
deflowestCommonAncestor(self, root: Optional['TreeNode'], p: 'TreeNode', q: 'TreeNode') -> Optional['TreeNode']:
ifnot root or root == p or root == q:
return root
left: Optional['TreeNode'] = self.lowestCommonAncestor(root.left, p, q)
right: Optional['TreeNode'] = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
return left if left else right