public class Solution {
// Recursively call lowestCommonAncestor to find node p and q,
// If found return, else return null
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return root;
if (root == p || root == q) // found a node, return itself
return root;
TreeNode left = lowestCommonAncestor(root.left, p, q); // find p and q in the left tree
TreeNode right = lowestCommonAncestor(root.right, p, q); // find p and q in the right tree
if (left != null && right != null) // both p and q can be found in the left and right tree, then root is the LCA
return root;
return left != null ? left : right; // return non-null node in left and right or null if both left and right are null
}
}
Leetcode 236. Lowest Common Ancestor of a Binary Tree
最新推荐文章于 2024-02-06 06:38:28 发布