Lowest-common-ancestor-of-a-binary-search-tree : Accepting a wrong solution


  • 0
    N

    Please add the some test cases to above problem.
    (https://discuss.leetcode.com/category/291/lowest-common-ancestor-of-a-binary-search-tree)

    It is accepted my wrong solution. Below is my wrong solution.

    My code should not accept the nodes which are not present in a tree. It is a bug in below code. Still, It is get accepted in leetcode.

    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      class Solution {
      public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
      if(root == null){
      return root;
      }
      if(root == p || root == q){
      return root;
      }

       TreeNode left = lowestCommonAncestor(root.left,p,q);
       TreeNode right = lowestCommonAncestor(root.right,p,q);
      
      if(left == null){
           return right;
       }
       if(right == null){
           return left;
       }
       
       if(left != null && right!=null){
      	return root;
      }
       
      return (root.left!=null)? root.left:root.right; 
      

      }
      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.