How is this java code wrong. Why does it fail ?

  • 1
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
    public class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            return null;
         if(root.val==p.val || root.val==q.val)
             return root;
         TreeNode leftsubTree=lowestCommonAncestor(root.left,p,q);
         TreeNode rightsubTree=lowestCommonAncestor(root.right,p,q);
         if(leftsubTree!=null &&rightsubTree!=null)
            return root;
            return leftsubTree;
            return rightsubTree;

  • 1

    When you're checking to see if the value of the root equals the value of node P or Q, that could lead to some logic errors. Instead just check to see if TreeNode Root is == TreeNode P or TreeNode Q.

  • 0

    @tbvho thanku for the reply and even though it solves my problem, i still don't get why comparing the nodes instead of the value inside them to lead to a problem. Can you please explain with example.

  • 1

    @khilji Since it didn't specify about duplicates, I solved the problem assuming that there could be duplicate values, so I was searching for the node rather than the first equal value it comes across. That way, I'd get the LCA.

Log in to reply

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