LeetCode236

  1. class Solution {
  2. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  3. if (root==null)
  4. return null;
  5. if (root.val==p.val || root.val==q.val)
  6. return root;
  7. TreeNode left=lowestCommonAncestor(root.left, p, q);
  8. TreeNode right=lowestCommonAncestor(root.right, p, q);
  9.  
  10. if (left==null)
  11. return right;
  12. if (right==null)
  13. return left;
  14. return root;
  15. }
  16. }