class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* temp = root;
if(temp == q || temp == p) {
return root;
}
while (temp!=NULL) {
if(IsNode(temp->left,p) && IsNode(temp->left,q)) temp = temp->left;
else if(IsNode(temp->right,p) && IsNode(temp->right,q)) temp = temp->right;
else break;
}
return temp;
}
bool IsNode(TreeNode* root,TreeNode* n) {
if(root == n) return true;
if(root == NULL) return false;
else return IsNode(root->right,n) || IsNode(root->left,n);
}
};