/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q){ auto res = lca(root, p, q); return cnt == 2 ? res : nullptr; }
TreeNode *lca(TreeNode* root, TreeNode* p, TreeNode* q){ if (!root) return root; auto l = lca(root->left, p, q); auto r = lca(root->right, p, q); if (root == p || root == q) { ++cnt; return root; } if (l && r) return root; return l ? l : r; }