int leftFist(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
int ret = 0;
if(root->left) {
ret = ret + leftFist(root->left, p, q);
}
if(root->right){
ret = ret+ leftFist(root->right, p, q);
}
if(root == p) {
ret +=1;
}
if(root == q) {
ret +=1;
}
return ret;
}
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
struct TreeNode* retRoot = NULL ;
int retSum = leftFist(root, p, q);
if(retSum == 2) {
int retSumleft = NULL;
if(root->left) {
retSumleft = leftFist(root->left, p, q);
}
if(0 < retSumleft && retSumleft < 2) {
return root;
}
int retSumright = NULL;
if(root->right) {
retSumright = leftFist(root->right, p, q);
}
if(0 < retSumright && retSumright< 2) {
return root;
}
}
if(root->left) {
retRoot = lowestCommonAncestor(root->left, p, q);
if(retRoot) {
return retRoot;
}
}
if(root->right){
retRoot = lowestCommonAncestor(root->right, p, q);
if(retRoot) {
return retRoot;
}
}
return retRoot;
}