I passed 29/31 tests ,but the rest 2 are weird... and I dont know what is wrong with my solution. COULD ANYONE HELP ME OUT?


  • 0
    F

    class Solution {
    public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    //int flag = 0;
    int pn = 0;
    int qn = 0;
    if(!root || p == root || q == root ) return root;

               RorL(root->right,p,pn);
               RorL(root->right,q,qn);
            
               
               if(pn != qn) 
               return root;
               else if(pn==1 && qn==1)
               return lowestCommonAncestor(root->right,p,q);
               else
               return lowestCommonAncestor(root->left,p,q);
                  
               
       
    }
    
    void RorL(TreeNode* root,TreeNode* node,int &flag){
         if(root == NULL) return ;
         else{
            TreeNode* tmp = root;
            if(tmp->val == node->val){
                flag = 1;
                return ;
            }
            else{
                 RorL(tmp->left,node,flag);
                 RorL(tmp->right,node,flag);
            }
         }
           
        return ;
    }
    

    };


  • 0
    F

    pn and qn indicates which side they are in the root. if pn ==1 , meaning TreeNode p is in the right side of root.


Log in to reply
 

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