C++ solution runtime error why?


  • 0
    K
    class Solution {
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            if(p==NULL) return q;
            if(q==NULL) return p;
            vector<TreeNode*> path1,path2;
            findpath(root,p,path1);
            findpath(root,q,path2);
            int i=0;
            while(i<path1.size()&&i<path2.size()&&path1[i]==path2[i])
                i++;
            return path1[i-1];
        }
        // find the path of a given TreeNode
        void findpath(TreeNode* root,TreeNode* p,vector<TreeNode*>& path)
        {
            if(root==NULL) return;
            if(root==p)
            {
                path.push_back(root);
                return;
            }
            findpath(root->left,p,path);
            if(path.size())
            {
                path.insert(path.begin(),root);
                return;
            }
            findpath(root->right,p,path);
            if(path.size())
            {
                path.insert(path.begin(),root);
                return;
            }
        }
    };

Log in to reply
 

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