Description
Submission
/**
* 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* ret = nullptr;
int dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr) return 0;
int left = dfs(root->left, p, q);
int right = dfs(root->right, p, q);
int cur = (root == p || root == q);
int count = left + right + cur;
if(count == 2 && !ret) {
ret = root;
}
return count;
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root, p, q);
return ret;
}
};