Accepted c++ 24 ms (with helper function)


  • 1
    H
    class Solution {
    public:
        void helper(TreeNode* root, TreeNode* p, TreeNode* q, bool &have_p, bool &have_q, TreeNode **ans) {
            if(root == NULL)
                return;
           
            bool have_p_left = false, have_q_left = false;
            helper(root->left, p, q, have_p_left, have_q_left, ans);
            
            bool have_p_right = false, have_q_right = false;
            helper(root->right, p, q, have_p_right, have_q_right, ans);
            
            have_p = have_p_left || have_p_right || root == p;
            have_q = have_q_left || have_q_right || root == q;
    
            if(have_p && have_q && *ans == NULL)
                *ans = root;
        }
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            bool have_p = false, have_q = false;
            TreeNode* ans = NULL;
            helper(root, p, q, have_p, have_q, &ans);
            return ans;
        }
    };

Log in to reply
 

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