/**
 * 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 p int整型 
     * @param q int整型 
     * @return int整型
     */

     vector<int> getpath(TreeNode* root,int p)
     {
        vector<int> path;

        TreeNode*node =root;
        while(node->val!=p)
        {
            path.push_back(node->val);
            if(p>node->val) node=node->right;
            else node=node->left;
        }
        path.push_back(node->val);
        return path;
     }
    int lowestCommonAncestor(TreeNode* root, int p, int q) {
        // write code here
        vector<int> path_p=getpath(root,p);
        vector<int> path_q=getpath(root,q);
        int res;

        for(int i=0;i<path_p.size()&&i<path_q.size();i++)
        {
            if(path_p[i]==path_q[i]) res=path_p[i];
            else continue;
        }
        return res;
    }
};