【二叉树】二叉树路径求和

题目(来源LintCode)

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
一个有效的路径,指的是从根节点到叶节点的路径。

代码实现思路:
1.使用递归,计算临时和值,和target进行比较,如果相等则得到一条搜索路径。
2.暴力求解,遍历出所有的根节点到子节点的路径,然后计算每条路径的和,找出所有符合要求的路径。(不推荐)

//借鉴了高手的思路做了一下,这里使用C++实现

#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;

class TreeNode {
public:
    int val;
    TreeNode *left, *right;
    TreeNode(int val) {
        this->val = val;
        this->left = this->right = NULL;
    }
};

class Solution {
public:
    /** * @param root the root of binary tree * @param target an integer * @return all valid paths */
#if 0
    //将树的所有可能路径遍历出,按路径求和
    vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
        vector<int> vec;
        vec.push_back(root->val);
        findOnePath(root,vec);
        return v;
    }

    void findOnePath(TreeNode *root,vector<int> vec){
        if (root == NULL){
            return;
        }

        if (root->left != NULL){
            vec.push_back(root->left->val);
            findOnePath(root->left, vec);
        }
        if (root->right != NULL){
            vec.push_back(root->right->val);
            findOnePath(root->right, vec);
        }
        if (root->left == NULL && root->right == NULL){
            v.push_back(vec);
        }
    }

    vector<vector<int>> v;
#else
    vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
        if (root == NULL){
            return v;
        }
        vector<int> vec;
        vec.push_back(root->val);
        findPath(root, root->val, target, vec);
        return v;
    }

    void findPath(TreeNode *root, int sum, int target, vector<int> vec)
    {
        //当前节点为叶子节点
        if (root->left == NULL && root->right == NULL){
            if (sum == target){
                v.push_back(vec);
                return;
            }
        }
        //不是叶子节点的情况处理
        int s = 0;
        if (root->left != NULL){
            //vec的拷贝构造函数
            vector<int> vm(vec);
            s = sum + root->left->val;
            vm.push_back(root->left->val);
            findPath(root->left,s,target,vm);
        }

        if (root->right != NULL){
            vector<int> vm(vec);
            s = sum + root->right->val;
            vm.push_back(root->right->val);
            findPath(root->right, s, target, vm);
        }
    }

    vector<vector<int>> v;
#endif
};

int main()
{
    TreeNode *root = new TreeNode(1);
    TreeNode *l1 = new TreeNode(2);
    TreeNode *r1 = new TreeNode(4);
    root->left = l1;
    root->right = r1;
    TreeNode *l2 = new TreeNode(3);
    TreeNode *r2 = new TreeNode(2);
    l1->left = l2;
    l1->right = r2;

    Solution sol;
    sol.binaryTreePathSum(root, 5);
    auto it = sol.v.begin();
    while (it != sol.v.end()){
        auto pit = it->begin();
        while (pit != it->end()){
            cout << *pit++ << " ";
        }
        cout << endl;
        ++it;
    }
    system("pause");
    return 0;
}
点赞