c++ solution


  • 0
    L
    /**
     * 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 {
        TreeNode * lcaFind(TreeNode * node, TreeNode *p, TreeNode * q){
            TreeNode * leftResult = node->left?lcaFind(node->left, p, q):NULL;
            TreeNode * rightResult = node->right? lcaFind(node->right, p, q):NULL;
            
            if((leftResult == q && rightResult ==p) || (leftResult == q && node == p)||
              (leftResult ==p && rightResult == q)|| (node ==p && rightResult == q)||
              (leftResult ==p && node == q)||(node ==q && rightResult == p)){
    
                return node;
            }
            if((leftResult||rightResult) && (node == p ||node == q)){
                return node;
            }
            if(leftResult == p||rightResult ==p||node == p){
                return p;
            }
            if(leftResult ==q||rightResult==q||node == q){
                return q;
            }
            if(leftResult) return leftResult;
            if(rightResult) return rightResult;
            return NULL;
        }
    public:
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            return lcaFind(root, p, q);
        }
    };
    

Log in to reply
 

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