题目描述:


/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param o1 int整型 
     * @param o2 int整型 
     * @return int整型
     */
    void findPath(TreeNode* root,vector<int> &v,int o,bool &findNode){
        if(!root) return;
        if(!findNode)//没找到正确路径,才将元素插入
            v.push_back(root->val);//插入节点元素
        if(root->val == o){
            findNode = true;
            return;
        }
        findPath(root->left, v, o, findNode);
        findPath(root->right, v, o, findNode);
        if(findNode) return;//放置将正确路径的元素删除
        v.pop_back();//弹出最后插入的一个元素
    }
    int lowestCommonAncestor(TreeNode* root, int o1, int o2) {
        // write code here
        //联想到二叉搜索树的最近公共祖先节点
        //题解1:使用两个数组,遍历数组
        vector<int> v1,v2;
        bool findNode = false;//用于记录是否为正确的路径
        findPath(root,v1,o1,findNode);
        findNode = false;//下一次查找结点2的路径时候,提前将findNode设置为false
        findPath(root, v2, o2, findNode);
        int len = min(v1.size(),v2.size());
        int i=0;
        cout<<v1.size()<<" "<<v2.size()<<endl;
        for(int i;i<len;i++){
            cout<<v1[i]<<" "<<v2[i]<<endl;
            if(v1[i] != v2[i])
                return v1[i-1];
        }
        return v1[len-1];
    }
};
/**
 * 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 sum int整型 
     * @return int整型
     */
    int result = 0;//结果作为全局变量
    void dfs(TreeNode* root, int sum){
        if(!root) return;
        sum-=root->val;
        if(sum == 0){
            result++;//注意:这里之后不能返回
        }
        dfs(root->left,sum);
        dfs(root->right,sum);
    }
    int FindPath(TreeNode* root, int sum) {
        // write code here
        if(!root) return result;
        dfs(root,sum);//先从根节点开始进行遍历
        FindPath(root->left,sum);//再遍历左子树
        FindPath(root->right,sum);//最后遍历右子树
        return result;
    }
};