Lowest Common Ancestor of a Binary Tree
/**
* 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
TreeNode *ansl,*ansr;
if(root==q || root==p ) return root;//理解这一步是很重要的 situation1
ansl=lowestCommonAncestor(root->left,p,q);
ansr=lowestCommonAncestor(root->right,p,q);
if(ansl!=NULL && ansr!=NULL) return root; //situation2
if(ansl!=NULL) return ansl;//situation3
if(ansr!=NULL) return ansr;//situation4
}
};