Non-recursive implement, return NULL if p, q or both are not in the three.

C++

```
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*> left_stack;
vector<TreeNode*> right_stack;
TreeNode* node = root;
TreeNode* lca = NULL;
while(node)
{
if(node == p || node == q)
if(lca == NULL)
lca = node;
else
return lca;
left_stack.push_back(node);
node = node->left;
}
while(left_stack.size() > 0)
{
node = left_stack.back();
if(node->right == NULL)
{
left_stack.pop_back();
if(node->left != NULL && node->left == lca)
lca = node;
continue;
}
if(right_stack.size() > 0 && node == right_stack.back())
{
left_stack.pop_back();
right_stack.pop_back();
if(lca != NULL && (node->left == lca || node->right == lca))
lca = node;
continue;
}
if(lca != NULL && (node->left == lca || node->right == lca))
lca = node;
right_stack.push_back(node);
node = node->right;
while(node)
{
if(node == p || node == q)
if(lca == NULL)
lca = node;
else
return lca;
left_stack.push_back(node);
node = node->left;
}
}
return NULL;
}
};
```