C++ recursion solution 44ms


  • 0
    P
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
    	TreeNode* lcNode = 0;
    	lowestCommonAncestorRec(root, p, q, &lcNode);
    	return lcNode;
    }
    
    bool lowestCommonAncestorRec(TreeNode* node, TreeNode* p, TreeNode* q, TreeNode** lcNode)
    {
    	if (!node)
    		return false;
    
    	bool nodeIsPQ = ((node == p) || (node == q));
    	bool gotPQonLeft = lowestCommonAncestorRec(node->left, p, q, lcNode);
    	bool gotPQonRight = (*lcNode) ? false : lowestCommonAncestorRec(node->right, p, q, lcNode);
    
    	if (*lcNode)
    		return true;
    
    	if ((nodeIsPQ && (gotPQonLeft || gotPQonRight)) || (gotPQonLeft && gotPQonRight))
    	{
    		*lcNode = node;
    		return true;
    	}
    
    	return nodeIsPQ || gotPQonLeft || gotPQonRight;
    }

Log in to reply
 

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