Where's my c++ code's problem?


  • 0
    J

    /**

    • Definition for a binary tree node.
    • struct TreeNode {
    • int val;
      
    • TreeNode *left;
      
    • TreeNode *right;
      
    • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
      
    • };
      */
      class Solution {
      public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL)
            return root;
        
        return findLCA(root, p->val, q->val);
    }
    
    TreeNode *findLCA(TreeNode *root, int n1, int n2){
        if (root == NULL)
            return root;
        
        if (root->val == n1 || root->val == n2)
            return root;
        
        TreeNode *left = findLCA(root->left, n1, n2);
        TreeNode *right = findLCA(root->right, n1, n2);
        
        if (left && right)
            return root;
        
        if (left)
            return left;
        else
            return right;
    }
    

    };

    I passed 29/31 but failed at this one:
    [37,-34,-48,null,-100,-100,48,null,null,null,null,-54,null,-71,-22,null,null,null,8], node with value -100, node with value -71

    I'm not familiar with this structure, so I don't know how this tree look like.

    Thanks in advance.


  • 3
    A

    It's probably because you are comparing value instead of reference/pointer.
    Judging from the sample you failed upon, duplicated values are allowed in the tree. So the right way to differentiate two nodes would be by comparing the reference/pointer.


Log in to reply
 

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