Time Cost

43min35s

Code

/**
 * 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 {
public:
    TreeNode* LCA = nullptr;
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root, p, q);
        return LCA;
    }

    int dfs(TreeNode* current, TreeNode* p, TreeNode* q) {
        if (LCA != nullptr) return 11;

        int current_num = 0;

        if (current->val == p->val) {
            current_num = 10;
        } else if (current->val == q->val) {
            current_num = 1;
        }

        int left = 0, right = 0;
        if (current->left != nullptr) {
            left = dfs(current->left, p, q);
        }

        if (current->right != nullptr) {
            right = dfs(current->right, p, q);
        }

        if (LCA == nullptr && current_num + left + right == 11) {
            LCA = current;
            return 11;
        }
        return current_num + left + right;
    }
};