/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    void dfs(TreeNode* root,stack<int>& s,int o)
    {
        if(!root)
        {
            
            return;
        }
        if(!s.empty()&&s.top()==o)
        {
            s.push(o);
        }
        else{
            s.push(root->val);
        }
        dfs(root->left,s,o);
        dfs(root->right,s,o);
        if(s.top()!=o) s.pop();

       
    }
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        if(o1==o2)
        {
            return o1;
        }
        // write code here
        stack<int> s1;
        stack<int> s2;
        dfs(root,s1,o1);
        dfs(root,s2,o2);
       while(s1.size()!=s2.size())
       {
            if(s1.size()>s2.size())
            {
                s1.pop();
            }
            else{
                s2.pop();
            }
       }
       while(s1.top()!=s2.top())
       {
        s1.pop();
        s2.pop();
       }
        return s1.top();
    }
};